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

前端 未结 2 876
孤城傲影
孤城傲影 2020-12-07 03:52

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

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

MyClass.prototype.showText = function() {
    al         


        
2条回答
  •  情话喂你
    2020-12-07 04:32

    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:

    • http://www.quirksmode.org/js/this.html

提交回复
热议问题