Javascript从事件处理程序获取对父对象/类的引用

我有一个类(或者包含函数的对象;我听说没有Javascript类这样的东西)叫做Foo,它有一个附加到click事件的事件处理程序。 调用事件处理程序时,我想修改我的类Foo的属性。 通常,我会使用this关键字,但在事件处理程序中, this引用设置为对html元素的引用。 这是我的代码:

 function Foo() { this.num=0; $('element').click(this.eventHandler);// jQuery to attach an onclick event to my element. this.eventHandler=function() { this.num++;// This doesn't work. // Normally, "this" would refer to my instance of Foo, // but as an event handler, "this" refers to the html element. } } 

所以我的问题是:如何将我的Foo实例引用到我的事件处理程序中,以便我可以修改其属性(如num )?

 function Foo() { var _self = this; this.num=0; $('element').click(this.eventHandler);// jQuery to attach an onclick event to my element. this.eventHandler=function() { _self.num++; } } 

使用引用_self = this在外部作用域中定义

你需要绑定函数的上下文; 否则this将是全局对象:

 $('element').click($.proxy(this.eventHandler, this)); 

在现代浏览器中,您还可以使用Function.prototype.bind

 $('element').click(this.eventHandler.bind(this)) 
 function Foo() { this.num=0; $(document).on('click', 'element', this, this.eventHandler); this.eventHandler=function(e) { var _this = e.data; _this.num++; } } 

1)使用JQuery on()方法附加事件侦听器。 2)使用引用_this来访问父类。

您可以在可以在事件处理程序中访问的构造函数中存储this的引用。

 function Foo() { this.num=0; $('element').click(this.eventHandler);// jQuery to attach an onclick event to my element. var that = this; this.eventHandler=function() { that.num++;// This doesn't work. } }