我使用单一方法在JavaScript中定义了一个类:
function MyClass(text) {
this.text = text;
}
MyClass.prototype.showText = function() {
alert(this.text);
}
然后,我使用jQuery定义了一个充当click事件处理程序的方法:
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();
};
当我点击按钮时,它无法说:
对象#< HTMLInputElement>没有方法'showText'
似乎jQuery点击事件处理程序中的this
引用了HTML元素本身,并且它没有引用MyClass
对象的实例。
我该如何解决这种情况?
jsFiddle:http://jsfiddle.net/wLH8J/
答案 0 :(得分:11)
这是预期的行为,请尝试:
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));
}
进一步阅读:
答案 1 :(得分: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);
}