我用一个方法在 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/