处理 jQuery 事件时在 JavaScript 类中覆盖的 'this' 关键字

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

本文关键字:关键字 this 覆盖 事件 jQuery JavaScript 处理      更新时间:2023-09-26

我用一个方法在JavaScript中定义了一个类:

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

然后,我使用 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();
};

当我单击该按钮时,它失败说:

对象 # 没有方法 'showText'

似乎 jQuery 点击事件处理程序中的this引用 HTML 元素本身,而不是引用MyClass对象的实例。

我该如何解决这种情况?

可用的 jsFiddle 可用: http://jsfiddle.net/wLH8J/

这是预期的行为,请尝试:

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 代理:

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

延伸阅读:

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

this是在调用函数时确定的,而不是在定义函数时确定的。您已将该函数复制到单击处理程序,因此当调用它时,它不会与MyClass相关联,并且this也不是您想要的。

您需要使用闭包将this的值存储在不同的变量中。

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