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中

猜你喜欢

转载自www.cnblogs.com/lujieting/p/10082423.html
今日推荐