一直以來,我對與 this 相關的東西總是有些模糊,例如 call、apply 等等。這次遇到一道和 bind 有關的筆試題,於是寫下這篇文章作為備忘。
bind 和 call、apply 一樣,都能夠改變上下文中 this 的指向。不同的是,call 與 apply 是直接在方法上呼叫使用,而 bind 在綁定 this 之後會「回傳一個方法」,但其內部核心其實還是 apply。
var obj = {
a: 1,
b: 2,
getCount: function(c, d) {
return this.a + this.b + c + d;
}
};
window.a = window.b = 0;
console.log(obj.getCount(3, 4)); // 10
var func = obj.getCount;
console.log(func(3, 4)); // 7為什麼會這樣?因為 func 在上下文中的 this 是 window!bind 的存在正是為了改變 this 的指向,以取得我們想要的值:
var obj = {
a: 1,
b: 2,
getCount: function(c, d) {
return this.a + this.b + c + d;
}
};
window.a = window.b = 0;
var func = obj.getCount.bind(obj);
console.log(func(3, 4)); // 10bind 是 function 的一個函式擴充方法,bind 之後程式碼重新綁定了 func 內部的 this 指向(obj),但它並不兼容 IE6~8,其相容寫法如下:
var obj = {
a: 1,
b: 2,
getCount: function(c, d) {
return this.a + this.b + c + d;
}
};
Function.prototype.bind = Function.prototype.bind || function(context) {
var that = this;
return function() {
return that.apply(context, arguments);
}
}
window.a = window.b = 0;
var func = obj.getCount.bind(obj);
console.log(func(3, 4)); // 10在我看來,bind 的核心在於「回傳一個尚未執行的方法」。如果直接使用 apply 或 call:
var ans = obj.getCount.apply(obj, [3, 4]); console.log(ans); // 10
就無法用簡寫的方式構造出 func 函式。因此改用 bind 傳遞 this 指向,再回傳一個尚未執行的方法,可說是一種相當巧妙的實作方式。