1. 程式人生 > >apply和call方法的使用

apply和call方法的使用

*apply和call都可以改變this的指向
*函式的呼叫,改變this的指向
*
* */

function f1(x,y) {
console.log((x+y)+"======"+this);
return "這是函式的返回值";
}
//apply和call的呼叫
var r1=f1.apply(null,[10,20]);//此時的f1中的this是window
console.log(r1);
var r2=f1.call(null,10,20);//此時的f1中的this是window
console.log(r2);
console.log("================");
//改變this指向
var obj={
sex:"男"
};
var r3=f1.apply(obj,[10,20]);//此時的f1中的this是obj
console.log(r3);
var r4=f1.call(obj,10,20);//此時的f1中的this是obj
console.log(r4);


//方法改變this指向
function Person(age) {
this.age=age;
}
Person.prototype.sayHi=function (x,y) {
console.log((x+y)+"======"+this.age);//例項物件===========
};
function Student(age) {
this.age=age;
}
var per=new Person(10);//例項物件
var stu=new Student(100);//例項物件
//sayHi方法是per的例項物件
per.sayHi.apply(stu,[10,20]);
per.sayHi.call(stu,10,20);

/*
* apply和call的使用方法
*
* apply的使用語法
* 函式名字.apply(物件,[引數1,引數2,····]);
* 方法名字.apply(物件,[引數1,引數2,····]);
* call的使用語法
* 函式名字.call(物件,引數1,引數2,····);
* 方法名字.call(物件,引數1,引數2,····);
*
* 作用:改變this的指向
* 不同的地方:引數傳遞的方式是不一樣的
*
* 只要是想使用別的物件的方法,並且希望這個方法是當前物件的,
那麼就可以使用apply或者是call的方法改變this的指向
*
* */


function f1() {
console.log(this+"=====呼叫了");
}
//f1是函式也是物件
console.dir(f1);
//物件呼叫方法,說明該物件中有這個方法
f1.apply();
f1.call();
console.log(f1.__proto__==Function.prototype);
//所有的函式都是Function的例項物件
console.log(Function.prototype);//ƒ () { [native code] }
console.log(Function);
//apply和call方法實際上並不函式這個例項物件中而是在Function的prototype中