bind() 方法會創建一個新函數。當這個新函數被調用時,bind() 的第一個
參數將作為它運行時的 this,之后的一序列參數將會在傳遞的實參前傳入
作為它的參數。(來自于 MDN )
bind 功能:
1 返回一個函數
2 可以傳入參數
關于指定 this 的指向,我們可以使用 call 或者 apply 實現
但是在這個寫法中,我們直接將 fBound.prototype = this.prototype,我們
直接修改 fBound.prototype 的時候,也會直接修改綁定函數的 prototype。
這個時候,我們可以通過一個空函數來進行中轉
測試
~~~
var value = 2;
var foo = {
value: 1
};
function bar(name, age) {
this.habit = 'shopping';
console.log(this.value);
console.log(name);
console.log(age);
}
bar.prototype.friend = 'kevin';
var bindFoo = bar.bind2(foo, 'daisy');
var obj = new bindFoo('18');
// undefined
// daisy
// 18
console.log(obj.habit);
console.log(obj.friend);
// shopping
// kevin
~~~
實現代碼
~~~
Function.prototype.bind2 = function(context) {
var that = this;
var args = Array.prototype.slice.call(arguments,1);
var fn = function(){}
var result = function() {
var bindArgs = Array.prototype.slice.call(arguments);
that.apply(this instanceof result ? this : context,args.concat(bindArgs));
}
fn.prototype = this.prototype;
result.prototype = Fn.prototype;
return result;
}
~~~