';这';处理jQuery事件时在JavaScript类中重写关键字

';这';处理jQuery事件时在JavaScript类中重写关键字,javascript,jquery,oop,prototype,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(thi

我用一个方法在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
对象的实例

我怎样才能解决这个问题


jsiddle可用:

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

function MyClass(text) {
    var self = this;

    this.text = text;
    $('#myButton').click(function () {
      self.button_click();
    });
}
或在较新的浏览器中(使用):

或者使用jquery:

进一步阅读:


在调用函数时确定,而不是在定义函数时确定。您已将该函数复制到click处理程序,因此当调用该函数时,它与
MyClass
没有关联,
this
不是您想要的

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

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

好极了,Yoshi,我来试试$.proxy这个东西,它看起来是我的完美解决方案,:-)@antur123不客气!就浏览器兼容性而言,代理可能是最安全的选择。
function MyClass(text) {
    this.text = text;
    $('#myButton').click($.proxy(this.button_click, this));
}
function MyClass(text) {
    this.text = text;
    var self = this;
    var click_handler = function () { self.button_click(); };
    $('#myButton').click(click_handler);
}