1. 作用
在特定的作用域调用函数,等于改变函数体内 this 的指向,以扩充函数赖以运行的作用域。
window.color="red";
var o={color:"blue"};
function getColor(){
console.log(this.color);
}
getColor.call(this); //red
getColor.call(window); //red
getColor.call(o); //blue
2. 区别
call:第一个参数是运行函数的作用域,其余参数都直接传递给函数,即传递给函数的参数必须逐个列举出来。
apply:第一个参数是运行函数的作用域 ,另一个参数是参数数组,可以是 Array 实例或 arguments 对象。
给出两段代码帮助理解:
function add(c, d){
return this.a + this.b + c + d;
}
var o = {a:1, b:3};
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16
add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34
function sum(num1,num2){
return num1+num2;
}
function callSum(num1,num2){
return sum.call(this,num1,num2);
}
function callSum(num1,num2){
return sum.apply(this,arguments);
}
function callSum(num1,num2){
return sum.apply(this,[num1,num2]);
}
3. 二者与 bind 的区别
bind 传参的方式和 call 相同;
call 与 apply 会立即执行函数,bind 不会