views:

56

answers:

1

I'm trying to use prototype inheritance in Javascript. The problem with my code below is that when the button is clicked and MyNamespace.MyObj.myEventHandler is called, the value of this is not the instance of MyNamespace.MyObj, but is instead the button that was clicked.

Am I structuring things wrong (is there a better way)? Can I somehow ensure that this is the instance of the object rather than the caller button?

var MyNamespace.MyObj = function(myform) {
  this.myform = myform;
  jQuery('.mybutton', this.myform).click(this.myEventHandler);
};

MyNamespace.MyObj.prototype = {
  myEventHandler: function() {
    this.myform.get(0).submit();
  }
};

jQuery(document).ready(function() {
  new MyNamespace.MyObj(jQuery('#myform'));
});

This is just a very dumbed down example that I'm using to learn prototype inheritance. I realize the actual function of the above code could be done simply in jQuery or that I could use an object literal or the Module pattern -- but I'm really just interested in learning the prototype inheritance rather than implementing a specific function at this time.

+5  A: 

There are various ways to preserve the this value, the most simple IMO is:

var MyNamespace.MyObj = function(myform) {
  var instance = this; // store `this`
  this.myform = myform;
  jQuery('.mybutton', this.myform).click(function () {
    instance.myEventHandler(); // use the stored value
  });
};
CMS
Excellent -- this works. Is this a common pattern to follow or can/should my code be structured in a way that this is not necessary, while achieving the same results?
RenderIn
@RenderIn: Yes I think it's the commonly used pattern, although there are [other ways](http://stackoverflow.com/questions/2025789/preserving-a-reference-to-this-in-javascript-prototype-functions)...
CMS
Proxy is probably the way to go: http://api.jquery.com/jQuery.proxy/
Julian Aubourg