【问题标题】:'this' keyword overriden in JavaScript class when handling jQuery events处理 jQuery 事件时 JavaScript 类中的“this”关键字覆盖
【发布时间】:2012-05-15 08:18: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 click 事件处理程序中的this 似乎是指HTML 元素本身,而不是指MyClass 对象的实例。

我该如何解决这种情况?

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

【问题讨论】:

    标签: javascript jquery oop prototype


    【解决方案1】:

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

    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));
    }
    

    进一步阅读:

    【讨论】:

    • 优秀的 Yoshi,我会试试 $.proxy 的东西,它看起来是我的完美解决方案,:-)
    • @antur123 不客气!代理可能是浏览器兼容性方面最安全的选择。
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2011-08-09
      • 1970-01-01
      • 2011-10-05
      • 2016-04-07
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 2019-11-18
      相关资源
      最近更新 更多