JavaScript - bind
// JavaScript - The bind method:
var hero = {
_name: 'John Doe',
getSecretIdentity: function (){
return this._name;
}
};
var stoleSecretIdentity = hero.getSecretIdentity.bind(hero);
console.log(stoleSecretIdentity());
In the above code, without using the .bind method, it would log undefined to
the console because the way that the stoleSecretIdentity method is invoked is
associate with the window object instead of the hero object.
The bind method takes one argument, the object to bind this function to, and
it returns a function that is bound to this object.
Consider:
var monica = {
name: 'Monica Geller',
total: 400,
deductMontlyFee: function(fee){
this.total = this.total - fee;
return this.name + ' remaining balance is '+ this.total;
}
}
If we bind the deductMontlyFee of monica with another object rachel and pass
rachel as first parameter of the bind function, rachel would be the value of this:
var rachel = {name: 'Rachel Green', total: 1500};
var rachelFeeDeductor = monica.deductMonthlyFee.bind(rachel, 200);
rachelFeeDeductor(); //"Rachel Green remaining balance is 1300"
rachelFeeDeductor(); //"Rachel Green remaining balance is 1100"
The bind method allows you to borrow a method and set the value of this without
calling the function. It simply returns an exact copy of the function with new
value of this. You can reuse the same function with new value of this without
harming the old one.
var ross = {name:'Ross Geller', total:250};
var rossFeeDeductor = monica.deductMonthlyFee.bind(ross, 25);
rossFeeDeductor(); //"Ross Geller remaining balance is 225"
rossFeeDeductor(); //"Ross Geller remaining balance is 200"
rachelFeeDeductor(); //"Rachel Green remaining balance is 900"
// Older browsers do not have the bind function. To provide a shim:
Function.prototype.bind = Function.prototype.bind || function(context){
var self = this;
return function(){
return self.apply(context, arguments);
};
}
page revision: 3, last edited: 14 Nov 2016 08:12