reperiendi

Using closures to fake ‘this’ in Javascript

Posted in Programming by reperiendi on 2006 December 2

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 Reply

You must be logged in to post a comment.