call apply bind 三者作用是改变某个函数的执行上下文(Execution Context),具体作用是改变函数体内部this的指向。
bind:
MDN
function.bind(thisArg[, arg1[, arg2[, …]]])
bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind()
的第一个参数,而其余参数将作为新函数的参数,供调用时使用。、
参数:
thisArg:调用绑定函数时作为 this 参数传递给目标函数的值。 如果使用new运算符构造绑定函数,则忽略该值。当使用 bind 在
setTimeout 中创建一个函数(作为回调提供)时,作为 thisArg 传递的任何原始值都将转换为 object。如果 bind
函数的参数列表为空,或者thisArg是null或undefined,执行作用域的 this 将被视为新函数的 thisArg。
arg1, arg2, …
当目标函数被调用时,被预置入绑定函数的参数列表中的参数。
mdn代码示例
const module = {
x: 42,
getX: function() {
return this.x;
}
};
const unboundGetX = module.getX;
console.log(unboundGetX());
// The function gets invoked at the global scope
// expected output:
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
解释:
const boundGetX = unboundGetX.bind(module);
- unboundGetX 复制了getX函数
- 绑定module为此函数的this
- 通过this访问module的东西。
- 返回函数(返回一个原函数的拷贝,并拥有指定的 this 值和初始参数。)
应用:
在默认情况下,使用 window.setTimeout() 时,this 关键字会指向 window (或
global)对象。当类的方法中需要 this 指向类的实例时,你可能需要显式地把 this 绑定到回调函数,就不会丢失该实例的引用。
apply:
MDN
func.apply(thisArg, [argsArray])
apply() 方法调用一个具有给定this值的函数,以及以一个数组(或类数组对象)的形式提供的参数。
var pokemon = {
firstname: 'Pika',
lastname: 'Chu ',
getPokeName: function() {
var fullname = this.firstname + ' ' + this.lastname;
return fullname;
}
};
var pokemonName = function(snack, hobby) {
console.log(this.getPokeName() + ' loves ' + snack + ' and ' + hobby);
};
pokemonName.call(pokemon,'sushi', 'algorithms');
// Pika Chu loves sushi and algorithms
pokemonName.apply(pokemon,['sushi', 'algorithms']);
// Pika Chu loves sushi and algorithms
call:
MDN
function.call(thisArg, arg1, arg2, …)
bind()和call()之间的主要区别在于call()方法:
- 接受其他参数
- 执行它立即调用的函数。
- call()方法不会复制正在调用它的函数。
call()和apply()用于完全相同的目的。它们之间的唯一区别是_ call()期望所有参数都单独传递,而apply()需要一个数组。例:
bind只是修改了this指向,而call与apply是修改this指向并且执行了
let obj = {
name: 'kobe'
};
function showName () {
console.log(this.name);
}
let testFunc = showName.bind(obj);
testFunc();
// showName.call(obj)
// showName.bind(obj)();等价
参考:MDN
https://segmentfault.com/a/1190000017462138