bind()
方法创建一个新的函数, 当这个新函数被调用时其this
置为提供的值,其参数列表前几项置为创建时指定的参数序列。
语法:
fun.bind(thisArg[, arg1[, arg2[, ...]]])
thisArg:当绑定函数被调用时,该参数会作为原函数运行时的 this 指向。当使用new
操作符调用绑定函数时,该参数无效。
arg1, arg2, ...:当绑定函数被调用时,这些参数将置于实参之前传递给被绑定的方法。
返回值 :
返回由指定的this
值和初始化参数改造的原函数拷贝
var module = {
x: 42,
getX: function() {
return this.x;
}
}
var unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined
var boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42
var module = {
x: 42,
getX: function() {
console.log('arguments',arguments)//bind剩下的参数在这里arguments里
return this.x;
}
}
var unboundGetX = module.getX;
var boundGetX = unboundGetX.bind(module,6,7,8);//注意后面的 6、7、8
console.log(boundGetX());
// "arguments" Object { 0: 6, 1: 7, 2: 8 }
// 42
更多内容:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind