In the past, you might have set self=this or that=this, etc., which of course will work, but using Function.prototype.bind() will be better and it will look more professional.
Here is a simple example:
The code copy is as follows:
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, to maintain the myObj context, a variable that=this is set, which works, but it doesn't look tidy without using Function.prototype.bind():
The code copy is as follows:
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 that implements .bind() is roughly like this:
Copy the code as follows: Function.prototype.bind = function (scope) {
var fn = this;
return function () {
return fn.apply(scope);
};
}
Here is a simple example of using Function.prototype.bind():
The code copy is as follows:
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 below IE8 and below do not support Function.prototype.bind(). Supported browsers include Chrome 7+, Firefox 4.0+, IE 9+, Opera 11.60+, Safari 5.1.4+. Although IE 8/7/6 and other browsers do not support it, the Mozilla development group wrote a function with similar functions for the old version of IE browser, with the code as follows:
The code copy 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;
};
}