在 JavaScript 裡,回呼函式中的 this 經常不是我們期待的那個物件。過去大家習慣先存一份 that = this 再使用,但其實 Function.prototype.bind() 才是更乾淨的做法。
render: function () {
var that = this;
this.getAsyncData(function () {
that.specialFunction();
that.anotherSpecialFunction();
});
}
這樣確實能動,但每個函式都得多背一個 that 變數,可讀性打了折扣。
render: function () {
this.getAsyncData(function () {
this.specialFunction();
this.anotherSpecialFunction();
}.bind(this));
}
bind() 會回傳一個新的函式,並把指定的物件固定為它的 this,之後無論怎麼呼叫都不會改變。最精簡的示範如下:
var foo = { x: 3 };
var bar = function () { console.log(this.x); };
bar(); // undefined
bar.bind(foo)(); // 3
bind() 本質上就是閉包加上 apply:
Function.prototype.bind = function (scope) {
var fn = this;
return function () {
return fn.apply(scope);
};
}
原生支援始於 Chrome 7、Firefox 4、IE 9、Opera 11.60、Safari 5.1.4;IE 8 及以下完全沒有這個方法。若專案仍需照顧舊版 IE,可放一份 polyfill,核心思路是先用切片取得額外參數,再透過 fNOP 保存原型鏈,讓 bind 出來的函式被 new 呼叫時行為仍然正確:
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
throw new TypeError("被綁定的目標不是可呼叫物件");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis ? this : oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
若使用 ES2015 以後的環境,箭頭函式也能解決大部分 this 指向的問題,但箭頭函式沒有自己的 this、也無法被 new,兩者並非完全等價,選用時要看你需要的語意。