DIV CSS 佈局教程網

深入認識 JavaScript 的 Function.prototype.bind
編輯:關於JavaScript     

函式綁定(Function binding)很可能是你開始使用 JavaScript 時最不關注的一點,但當你意識到需要在另一個函式中保持 this 上下文時,你真正需要的其實就是 Function.prototype.bind()。

第一次遇到這個問題時,你可能傾向於把 this 存到一個變數上(常見命名如 self、_this、context 或 that),以便在改變上下文後繼續引用。這些做法都可行,但其實有更好、更專用的方式。

來看下面的例子,我們名正言順地把上下文快取到變數中:

 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' 的錯誤。改用 bind 則能更簡潔:

 render: function () {
 this.getAsyncData(function () {
 this.specialFunction();
 this.anotherSpecialFunction();
 }.bind(this));
} 

bind() 會建立一個新函式,當它被呼叫時,其 this 會被設定為傳入的值。我們把 this(也就是 myObj)傳進 bind(),回呼函式執行時 this 便指向 myObj。其內部實作概念上如下:

 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
var boundFunc = bar.bind(foo);
boundFunc(); // 3

瀏覽器支援方面,Chrome 7、Firefox 4、IE 9、Opera 11.60、Safari 5.1.4 以上皆支援,但 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;
 };
} 

適用的場景

點擊處理函式:例如要記錄點擊次數時,可避免多寫一層匿名函式:

 var logger = {
 x: 0,
 updateCount: function(){
 this.x++;
 console.log(this.x);
 }
}
document.querySelector('button').addEventListener('click', logger.updateCount.bind(logger));

setTimeout:使用模板引擎或某些 MV* 框架時,渲染後立即存取新 DOM 節點常有時序競爭問題,可用 bind 搭配 setTimeout 解決:

 afterRender: function () {
 this.$el.find('select').myPlugin();
},
render: function () {
 this.$el.html(this.template());
 setTimeout(this.afterRender.bind(this), 0);
}

掌握 bind 之後,就能優雅地處理大量需要維持 this 上下文的場合。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved