過去我們常在函數裡寫 var self = this 或 var that = 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();
這裡為了保住 myObj 的上下文而設了 that = this,雖然能動,卻不如 bind() 來得乾淨:
render: function () {
this.getAsyncData(function () {
this.specialFunction();
this.anotherSpecialFunction();
}.bind(this));
}
呼叫 .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
var boundFunc = bar.bind(foo);
boundFunc(); // 3
相當好用,對吧?遺憾的是 IE8 及以下並不支援 Function.prototype.bind()。支援的瀏覽器包括 Chrome 7+、Firefox 4.0+、IE 9+、Opera 11.60+、Safari 5.1.4+。對於舊版 IE,Mozilla 開發團隊提供了功能相近的相容寫法:
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;
};
}