Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

'this' keyword overriden in JavaScript class when handling jQuery events

I have defined a class in JavaScript with a single method:

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

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

Then, I defined a method that acts as a handler for a click event, 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 click the button, it fails saying:

Object #<HTMLInputElement> has no method 'showText'

It seems to be that this in jQuery click event handler refers the HTML element itself, and it does not refer the instance of the MyClass object.

How can I solve this situation?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's an expected behaviour, try:

function MyClass(text) {
    var self = this;

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

or in newer browsers (using bind):

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

or using jquery proxy:

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

further reading:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...