In the past, you might directly set self=this or that=this, etc., which of course would work, but using Function.prototype.bind() would be better and look more professional.
Here’s a simple example:
var myObj = {
specialFunction: function () {
},
anotherSpecialFunction: function () {
},
getAsyncData: function (cb) {
cb();
},
render: function () {
var that = this;
this.getAsyncData(function () {
that.specialFunction();
that.anotherSpecialFunction();
});
}
};
myObj.render();
In this example, in order to maintain the myObj context, a variable that=this is set, which is feasible, but Function.prototype is not used .bind() looks neater:
render: function () {
this.getAsyncData(function () {
this.specialFunction();
this.anotherSpecialFunction();
}.bind(this));
}
When calling .bind(), it will simply create a new function and pass this to this function. The code to implement .bind() is roughly like this:
Function.prototype .bind = function (scope) {
var fn = this;
return function () {
return fn.apply(scope);
};
}
Look at a simple example of using Function.prototype.bind():
var foo = {
x: 3
};
var bar = function(){
console.log(this.x);
};
bar(); // undefined
var boundFunc = bar.bind(foo);
boundFunc(); // 3
Isn’t it very useful! Unfortunately, IE browsers IE8 and below do not support Function.prototype.bind(). Supported browsers are Chrome 7, Firefox 4.0, IE 9, Opera 11.60, Safari 5.1.4. Although browsers such as IE 8/7/6 do not support it, the Mozilla development team has written a function with similar functions for older versions of IE browsers. The code is as follows:
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable 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;
};
}