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

前端 未结 2 878
孤城傲影
孤城傲影 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:19

    this is determined when a function is called, not when it is defined. You have copied the function to the click handler, so when it is called it isn't associated with MyClass and this isn't what you want it to be.

    You need to use a closure to store the value of this in a different variable.

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

提交回复
热议问题