Introduction to the prototype.bind of method in JavaScript
- 2020-03-30 02:34:43
- OfStack
Previously, you might have just set self=this, that=this, etc., which of course works, but using function.prototype.bind () is better and looks 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, to keep myObj in context, a variable that=this is set, which is fine, but looks cleaner without using function.prototype.bind () :
render: function () {
this.getAsyncData(function () {
this.specialFunction();
this.anotherSpecialFunction();
}.bind(this));
}
When.bind() is called, it simply creates a new function and passes this to it. The code for.bind() looks something like this:
Function.prototype.bind = function (scope) {
var fn = this;
return function () {
return fn.apply(scope);
};
}
Here's 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