我有一个类(或者包含函数的对象;我听说没有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.
}
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:如何在我的事件处理程序中引用我的Foo实例,以便我可以修改其属性(如num)?