一、这两个方法的作用是什么?
这两个方法都会以指定的 this 值来调用函数,即会设置调用函数时函数体内 this 对象的值。
二、apply()
apply() 方法接收两个参数:函数内 this 的值和一个参数数组。第二个参数可以是 Array 的实例,但也可以是 arguments 对象。
示例:传入arguments 对象
(
function testApplyArguments() {
function sum(num1,num2) {
return num1+num2;
}
function callsum1(num1,num2) {
console.log(this);
console.log("testApplyArguments");
return sum.apply(this,arguments);
}
console.log(callsum1(10,10));
}
)();
示例:传入Array对象
(
function testApplyArray() {
function sum(num1,num2) {
return num1+num2;
}
function callsum1(num1,num2) {
console.log(this);
console.log("testApplyArray");
return sum.apply(this,[num1,num2]);
}
console.log(callsum1(10,10));
}
)();
三、call()
示例:逐个传递参数
(function testCall() {
function sum(num1,num2) {
return num1+num2;
}
function callsum1(num1,num2) {
console.log(this);
console.log("testCall");
return sum.call(this,num1,num2);
}
console.log(callsum1(10,10));
})();
这里的 callSum() 函数必须逐个地把参数传给 call() 方法。
四、call和apply的真正意图
apply() 和 call() 真正强大的地方并不是给函数传参,而是控制函数调用上下文即函数体内 this值的能力。
(function testRealmean() {
global.color = 'red';
let mycolor = {
color : 'pink'
}
function showColor() {
console.log(this.color);
}
showColor();
showColor.call(mycolor);
})();
五、bind()
bind() 方法会创建一个新的函数实例,其 this 值会被绑定到传给 bind() 的对象。
(function testBind() {
global.color = 'red';
let mycolor = {
color : 'pink'
}
function showColor() {
console.log(this.color);
}
let showColorBind = showColor.bind(mycolor);
showColorBind();
})();
bind()会返回一个绑定了this的新函数,即使在全局作用域下调用,他的this值也不是global,而是bind()指定的对象参数。