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

Joe*_*oel 9 javascript oop jquery class javascript-events

我有一个类(或者包含函数的对象;我听说没有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)?

fca*_*ran 15

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++;
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Thi*_*ter 13

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

$('element').click($.proxy(this.eventHandler, this));
Run Code Online (Sandbox Code Playgroud)

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

$('element').click(this.eventHandler.bind(this))
Run Code Online (Sandbox Code Playgroud)