Javascript get reference to parent object/class fr

2019-01-24 08:39发布

I have a class (or function-containing object; I've heard that there is no such thing as a Javascript class) called Foo, with an event handler that is attached to a click event. When the event handler is called, I want to modify a property of my class Foo. Normally, I would use the this keyword, but in the event handler, the this reference is set to the reference to the html element. Here is my code:

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.
    }
}

So my question is: how do I get a reference to my instance of Foo into my event handler so that I can modify its properties (like num)?

4条回答
Summer. ? 凉城
2楼-- · 2019-01-24 08:58
function Foo() {
   this.num=0;
   $(document).on('click', 'element', this, this.eventHandler);
   this.eventHandler=function(e) {
      var _this = e.data; 
      _this.num++;
   }
}

1) Use JQuery on() method to attach event listeners. 2) Use a reference _this for accessing parent class.

查看更多
叛逆
3楼-- · 2019-01-24 09:02
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++;
    }
}

use a reference _self = this defined in the outer scope

查看更多
\"骚年 ilove
4楼-- · 2019-01-24 09:11

You can store a reference to this in the constructor that you can access in your event handler.

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.
    }
}
查看更多
我命由我不由天
5楼-- · 2019-01-24 09:13

You need to bind the function's context; otherwise this will be the global object:

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

In a modern browser you can also use Function.prototype.bind:

$('element').click(this.eventHandler.bind(this))
查看更多
登录 后发表回答