javascript - 处理 jQuery 事件时 JavaScript 类中的“this”关键字覆盖

标签 javascript jquery oop prototype

我用一个方法在 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();
};

当我点击按钮时,它没有显示:

Object #<HTMLInputElement> has no method '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 proxy :

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

进一步阅读:

关于javascript - 处理 jQuery 事件时 JavaScript 类中的“this”关键字覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10596727/

相关文章:

javascript - MVC Ajax调用问题

具有单个输入字段的表单的 jQuery 提交处理程序不会在 IE 上触发

Java - 定义用于创建对象的行,而不是仅使用方法

javascript - 根据输入的 Mongoose 数组查找元素

javascript - 如何在javascript中进行统一交叉?

javascript - 为什么 clean 命令在 Gradle React native 项目中不起作用?

android - 在Android上使用Phonegap,电子邮件数组为contacts.find返回null

JQuery float 饼图大小错误

c++ - 私有(private)继承与公开迭代器

Python 和类