处理jQuery事件时,'this'关键字在JavaScript类中重写 [英] 'this' keyword overriden in JavaScript class when handling jQuery events

查看:134
本文介绍了处理jQuery事件时,'this'关键字在JavaScript类中重写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have defined a class in JavaScript with a single method:

function MyClass(text) {
    this.text = text;
}

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

然后,我定义了一个充当click事件处理程序的方法,使用jQuery:

Then, I defined a method that acts as a handler for a click event, using 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();
};

当我点击按钮时,它无法说:

When I click the button, it fails saying:


Object#< HTMLInputElement>没有方法'showText'

Object #<HTMLInputElement> has no method 'showText'

在jQuery中似乎是这个 click事件处理程序引用HTML元素本身,它不引用 MyClass 对象的实例。

It seems to be that this in jQuery click event handler refers the HTML element itself, and it does not refer the instance of the MyClass object.

如何我可以解决这种情况吗?

How can I solve this situation?

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

jsFiddle available: http://jsfiddle.net/wLH8J/

推荐答案

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

That's an expected behaviour, try:

function MyClass(text) {
    var self = this;

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

或在较新的浏览器中(使用 bind ):

or in newer browsers (using bind):

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

或使用jquery 代理

or using jquery proxy:

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

进一步阅读:

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

这篇关于处理jQuery事件时,'this'关键字在JavaScript类中重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆