對bind的總結
阿新 • • 發佈:2020-12-20
語法:
bind() 方法的主要作用就是將函式繫結至某個物件,bind()
方法會建立一個函式,函式體內this物件的值會被繫結到傳入bind()
函式的值。
bind的定義:
bind() 函式會建立一個新函式(稱為繫結函式),新函式與被調函式(繫結函式的目標函式)具有相同的函式體。當目標函式被呼叫時 this 值繫結到bind()
的第一個引數,該引數不能被重寫。
實現物件繼承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var A = function (name) {
this .name = name;
}
var B = function () {
A.bind( this , arguments);
}
B.prototype.getName = function () {
return this .name;
}
var b = new B( "hello" );
console.log(b.getName()); // "hello"
|
bind()的相容性寫法
1 2 3 4 5 6 7 8 9 10 11 12 |
if (!Function.prototype.bind) {
Function.prototype.bind = function () {
var self = this , // 儲存原函式
context = [].shift.call(arguments), // 需要繫結的this上下文
args = [].slice.call(arguments); // 剩餘的引數轉成陣列
return function () { // 返回一個新函式
// 執行新函式時,將傳入的上下文context作為新函式的this
// 並且組合兩次分別傳入的引數,作為新函式的引數
return self.apply(context, [].concat.call(args, [].slice.call(arguments)));
}
};
}
|
bind與 call/apply方法的區別
共同點:
都可以改變函式執行的上下文環境;
不同點:
bind: 不立即執行函式,一般用在非同步呼叫和事件; call/apply: 立即執行函式。