Ger*_*rre 3 javascript oop jquery prototype
我用JavaScript在单个方法中定义了一个类:
function MyClass(text) {
this.text = text;
}
MyClass.prototype.showText = function() {
alert(this.text);
}
Run Code Online (Sandbox Code Playgroud)
然后,我使用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();
};
Run Code Online (Sandbox Code Playgroud)
当我点击按钮时,它无法说:
对象#<HTMLInputElement>没有方法'showText'
似乎this在jQuery中,click事件处理程序引用HTML元素本身,并且它不引用该MyClass对象的实例.
我该如何解决这种情况?
jsFiddle可用:http://jsfiddle.net/wLH8J/
Yos*_*shi 11
这是预期的行为,尝试:
function MyClass(text) {
var self = this;
this.text = text;
$('#myButton').click(function () {
self.button_click();
});
}
Run Code Online (Sandbox Code Playgroud)
或者在较新的浏览器中(使用bind):
function MyClass(text) {
this.text = text;
$('#myButton').click(this.button_click.bind(this));
}
Run Code Online (Sandbox Code Playgroud)
或使用jquery 代理:
function MyClass(text) {
this.text = text;
$('#myButton').click($.proxy(this.button_click, this));
}
Run Code Online (Sandbox Code Playgroud)
进一步阅读: