'this' keyword is overridden in javascript class when handling jQuery events

I defined the class in JavaScript using one method:

function MyClass(text) {
    this.text = text;
}

MyClass.prototype.showText = function() {
    alert(this.text);
}

Then I defined a method that acts as a click event handler using jQuery:

function MyClass(text) {
    this.text = text;
    $('#myButton').click(this.button_click);
}

MyClass.prototype.showText = function() {
    alert(this.text);
};

MyClass.prototype.button_click = function() {
    this.showText();
};

When I press the button, it does not say:

Object # <HTMLInputElement> does not have a 'showText' method

It seems that thisin the jQuery event handler click refers to the HTML element itself and does not apply to the instance of the object MyClass.

How can I solve this situation?

jsFiddle is available: http://jsfiddle.net/wLH8J/

+3
source share
2 answers

What is the expected behavior, try:

function MyClass(text) {
    var self = this;

    this.text = text;
    $('#myButton').click(function () {
      self.button_click();
    });
}

( bind):

function MyClass(text) {
    this.text = text;
    $('#myButton').click(this.button_click.bind(this));
}

jquery proxy:

function MyClass(text) {
    this.text = text;
    $('#myButton').click($.proxy(this.button_click, this));
}

:

+11

this , , . , , , MyClass, this - , .

, this .

function MyClass(text) {
    this.text = text;
    var self = this;
    var click_handler = function () { self.button_click(); };
    $('#myButton').click(click_handler);
}
+2

All Articles