nvcnvn
nvcnvn

Reputation: 5175

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!

Upvotes: 0

Views: 449

Answers (4)

dfsq
dfsq

Reputation: 193261

You can call prototype methods from constructor. You problem is that you are loosing context inside anonymous click function. So you have two options:

// 1. link to original object
var self = this;
$("#button1").click(function() {
    self.Hide();
});

// 2. use proxy (bind) to invoke method in correct context
// there is built in function available in jQuery
$("#button1").click($.proxy(function() {
    this.Hide();
}, this));

Upvotes: 0

Laurent
Laurent

Reputation: 3837

$("#button1").click(function() {
  //How can I call hide
  this.Hide()//Error
});

In this line of code, this refers to the button (it's inside a function). Before ths binding, you can define var that = this; and use thatin the callback:

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

function MyClass() {
  var that = this;
  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
    that.Hide();
  });
}
MyClass.prototype.Hide = function() {
  this.layout.hide("slow");
}

Upvotes: 2

zzzzBov
zzzzBov

Reputation: 179046

You're not calling Hide in the constructor. You're calling it in the click callback, which has a different context (this is different).

Use a temp variable to store a reference to the current object:

var t;
t = this;

...click(function () {
  t.hide();
});

Also, JavaScript convention is that PascalCase is used for constructors, and camelCase is used for functions/methods.

Upvotes: 1

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107508

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();
});
...

Upvotes: 2

Related Questions