Search code examples
javascriptjqueryoopmethodsprototype-programming

How to use prototype method in class constructor


I habe read here about defining method for a Javascript class Advantages of using prototype, vs defining methods straight in the constructor? and I choose prototype way. But I get an issue, for example:

function MyClass() {};
MyClass.prototype.Hide = function() {};

function MyClass() {
  this.layout = $("<div>", {id: "layout1"}).text("My content");
  this.button = $("<input />", {id: "button1"});
  this.layout.append(this.button);
  $("#button1").click(function() {
    //How can I call hide
    this.Hide()//Error
  });
}
MyClass.prototype.Hide = function() {
  this.layout.hide("slow");
}

How can I call the prototype function in the contructor? I have try the forward declaration for the prototype method, but I think the issue is the way I call it, this.Hide() is no help!
Thanks for your time!


Solution

  • You're using the wrong this. The this you're using to call Hide() is actually the #button element. Assign the this that is the MyClass object to a local variable, and then use that in the click delegate:

    ...
    this.layout.append(this.button);
    var $this = this;
    $("#button1").click(function() {
        $this.Hide();
    });
    ...