函式綁定(function binding)大概是開始學 JavaScript 時最不被重視的課題。直到你發現「在另一個函式裡 this 變了」,才意識到自己真正需要的就是 Function.prototype.bind()——而且往往還沒意會到這一點。
最常見的場景是異步回呼。看下面的程式:
var myObj = {
specialFunction: function () {},
anotherSpecialFunction: function () {},
getAsyncData: function (cb) { cb(); },
render: function () {
var that = this;
this.getAsyncData(function () {
that.specialFunction();
that.anotherSpecialFunction();
});
}
};
myObj.render();
如果直接寫 this.specialFunction(),會得到:
Uncaught TypeError: Object [object global] has no method 'specialFunction'
原因是回呼函式被執行時,this 已經不是 myObj 了(在 strict mode 下是 undefined,非 strict mode 下會指向 window)。所以我們需要把上下文存到一個變數(常見命名是 self、_this、context 或 that),之後再引用它。
這種做法沒錯,但有更好、更專門的方式。
render: function () {
this.getAsyncData(function () {
this.specialFunction();
this.anotherSpecialFunction();
}.bind(this));
}
.bind() 會回傳一個新函式,這個新函式被呼叫時,其 this 會被固定成 bind 時傳入的值。所以我們把想要的上下文(這裡是 myObj)傳進去,之後不論這個回呼在哪裡被執行,this 都指向 myObj。
注意 bind 與 call / apply 的差別:後兩者會立刻執行函式,bind 則只是「預先綁好 this,之後再執行」。
它的內部實作其實非常單純:
Function.prototype.bind = function (scope) {
var fn = this;
return function () {
return fn.apply(scope);
};
};
再看一個最小用例:
var foo = { x: 3 };
var bar = function () { console.log(this.x); };
bar(); // undefined(this 是全域物件)
var boundFunc = bar.bind(foo);
boundFunc(); // 3
支援情況:Chrome 7+、Firefox 4+、IE 9+、Opera 11.60+、Safari 5.1+。
也就是說 IE8 及以下不支援,若需要兼顧,MDN 提供了可靠的替代實作:
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
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;
};
}
這段 polyfill 之所以看起來複雜,是因為它額外處理了「bind 後的函式被當作建構函式呼叫」的情況——透過 fNOP 保留原型鏈,讓 new boundFunc() 也能正確運作。
var logger = {
x: 0,
updateCount: function () {
this.x++;
console.log(this.x);
}
};
常見寫法要包一層匿名函式:
document.querySelector('button')
.addEventListener('click', function () { logger.updateCount(); });
用 bind 就乾淨多了:
document.querySelector('button')
.addEventListener('click', logger.updateCount.bind(logger));
用過模板引擎或 MV* 框架的人大概遇過這個問題:渲染完模板後立刻要選取新的 DOM 節點,卻發現找不到。
var myView = {
template: '/* 含有 <select /> 的樣板字串 */',
$el: $('#content'),
afterRender: function () {
this.$el.find('select').myPlugin();
},
render: function () {
this.$el.html(this.template());
this.afterRender();
}
};
myView.render();
這是個時序競爭問題:如果 DOM 節點還沒插入文件樹,find('select') 自然找不到東西。把 afterRender 延後到下一輪事件循環執行就能避開:
render: function () {
this.$el.html(this.template());
setTimeout(this.afterRender, 0);
}
但這樣會得到「找不到 afterRender」的錯誤——因為 setTimeout 回呼中的 this 又變了。加上 bind 即可:
render: function () {
this.$el.html(this.template());
setTimeout(this.afterRender.bind(this), 0);
}
ES6 的箭頭函式解決了絕大多數 this 困擾,因為它沒有自己的 this,會沿用外層作用域:
render() {
this.getAsyncData(() => {
this.specialFunction();
this.anotherSpecialFunction();
});
}
但兩者並非可以完全互相取代:箭頭函式無法用 call/apply/bind 改寫 this,也不能當建構函式;而 bind 的強項是「預先產生一個綁好上下文的函式」,可以重複傳遞使用,例如當回呼、當事件處理器、當排序比較函式。理解兩者的分工,才是真正掌握 this 的開始。