bind方法介紹
bind() 方法會創(chuàng)建一個新函數(shù)。當這個新函數(shù)被調(diào)用時绕德,bind() 的第一個參數(shù)將作為它運行時的 this,之后的一序列參數(shù)將會在傳遞的實參前傳入作為它的參數(shù)摊阀。
例子:
var foo = {
value: 'abc'
}
function bar(a, b) {
console.log(this.value)
console.log(a)
console.log(b)
}
var bindFoo = bar.bind(foo,1)
bindFoo(2) // 輸出 abc 1 2
實現(xiàn)bind方法的問題:
1耻蛇、返回一個函數(shù)
2、可以傳入?yún)?shù)
3胞此、返回參數(shù)
4臣咖、構造函數(shù)效果
5、調(diào)用判斷
Function.prototype.bind2 = function (context) {
// 如果不是函數(shù)調(diào)用報錯
if (typeof this !== "function") {
throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
}
var self = this;
// 獲取第一次bind時傳參 bar.bind(foo,1) 獲取參數(shù) 1
var args = Array.prototype.slice.call(arguments, 1);
var fNOP = function () { }; // 中轉(zhuǎn)函數(shù)
var fBound = function () {
// 獲取調(diào)用時函數(shù)的參數(shù) bindFoo(2) 獲取到2參數(shù)
var bindArgs = Array.prototype.slice.call(arguments);
//---------------如果是new this失效 指向?qū)嵗#绻皇莕ew 則指向bind第一個參數(shù)
return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs)); // 調(diào)用函數(shù)夺蛇,并返回值。
}
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound; // 返回函數(shù)
}
詳細文章推薦 JavaScript深入之bind的模擬實現(xiàn)