Using closures to fake ‘this’ in Javascript
Say you’ve got two instances a, b of a class A in Javascript. You’d like to add a class method f to the object a without changing b. If not for that, you could add the function to the prototype:
A.prototype.f=function(){
return this.g()+1;
}
One way is to use multiple inheritance:
function F(){
this.f=function(){
return this.g()+1;
}
}
F.call(a);
Another is to use a closure to send in a reference to a:
a.f=(function(self){
return function(){
return self.g()+1;
}
})(a);
which is sometimes easier than multiple inheritance.
leave a comment