处理jQuery事件时,’this’关键字在JavaScript类中重写

我用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(); }; 

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

对象#没有方法’showText’

似乎this在jQuery click事件处理程序中引用了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 代理 :

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

进一步阅读:

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

您需要使用闭包将此值存储在另一个变量中。

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