Function.prototype.bind = function() {
var self = this; // 保存原函數
var context = Array.prototype.shift.call(arguments); // 需要綁定的this上下文
var argsArray = Array.prototype.slice.call(arguments); // 剩余參數轉成數組
return function() { // 返回新函數
return that.apply(context, Array.prototype.concat.apply(argsArray, Array.prototype.slice.call(arguments)));
// 執行新函數的時候,會把之前傳入的context當作新函數的體內的this,并組合兩次分別傳入的參數,作為新函數的參數
}
}
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);
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。