call()和apply()都是在特定的作用域中调用函数,等于设置函数体内this对象的值,以扩充函数赖以运行的作用域。
一般来说,this总是指向调用某个方法的对象,但是使用call()和apply()方法时,就会改变this的指向。
function fun(){
console.log(this);
}
fun();
- 上面,当我们调用fun()函数的时候, this的指向是window
function fun(){
console.log(this);
}
var obj1={
type:"我是obj1",
sayName:function(){
console.log(this.type);
}
};
var obj2={
type:"我是obj2"
};
/*this 永远是window*/
fun(obj1);
/*this是传入的参数*/
fun.call(obj1);
fun.apply(obj2);
/*正常对象里的方法 this 指向上级function*/
obj1.sayName();
/*指定参数 this指向传入的参数*/
obj1.sayName.apply(obj2);
</script>
-
打印结果:
Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
{type: “我是obj1”, sayName: ƒ}
{type: “我是obj2”}
我是obj1
我是obj2 -
说明: fun()默认this指向window, 当我们在调用fun使用call/apply()方法,并且向方法里面传递一个参数的时候, this的指向就会发生变化, 指向到传递过来的参数对象。
call()和apply()方法除了传递对象之外, 还可以传递函数形参,括号里第一个是要传递的对象, 后面的是函数需要的参数。call()和apply()的写法不同, call(obj,xx,xx,xx) 。 apply(obj,[xx,xx,xx])。
function fun(a,b,c){
console.log(this);
console.log(a+b+c);
}
var obj1={
type:"我是obj1"
};
fun.call(obj1,2,3,4);
- 运行结果:
{type: “我是obj1”}
9