Function.prototype.bind = function() {
var self = this; // 保存原函數(shù)
var context = Array.prototype.shift.call(arguments); // 需要綁定的this上下文
var argsArray = Array.prototype.slice.call(arguments); // 剩余參數(shù)轉(zhuǎn)成數(shù)組
return function() { // 返回新函數(shù)
return that.apply(context, Array.prototype.concat.apply(argsArray, Array.prototype.slice.call(arguments)));
// 執(zhí)行新函數(shù)的時候炉爆,會把之前傳入的context當作新函數(shù)的體內(nèi)的this罗捎,并組合兩次分別傳入的參數(shù),作為新函數(shù)的參數(shù)
}
}
var obj = {
name: 'u14e'
};
var func = function(a, b, c, d) {
console.log(this.name); // u14e
console.log([a, b, c, d]); // [1, 2, 3, 4]
}.bind(obj, 1, 2);
func(3, 4);
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者