简体   繁体   中英

Which solution is better for passing “this” parameter to javascript event handler

What is the best approach for passing the this parameter of the init function to the change event handler and why?

Option 1 (using that = this).

SomeObject.prototype.init = function () {
    var that = this;
    this.$element.change(function () {            
        //do some some things with that.
        that.
    });

};

Option 2 (using event.data ).

SomeObject.prototype.init = function () {

    this.$element.change({object:this }, function (e) {            
        //do some some things with the event data.
        e.data.object.
    });

};

Or another (better) one?

Imho the first one is a bit nicer. A 3rd way (if you can use ECMA5) would be

SomeObject.prototype.init = function () {
   this.$element.change(function () {            
       //do some some things with this.
       this.
    }.bind(this));
};

If you want this inside the event handler to refer to this , of the "parent function", you can use $.proxy [docs] :

this.$element.change($.proxy(function (e) {            
    //do some some things with the event data.
}, this));

But then you have to access event.currentTarget [docs] to get a reference to the element the event handler is bound to.

Apart from that, choose whatever makes most sense to you / you feel most comfortable with and be consistent.

I tend to wrap the function that needs the reference in a function that holds it, like this:

this.$element.change(function(parent) {
    return function() {
        // do some things with parent.
    }
}(this));

I wouldn't say that one approach is better than the other. It's just that if I use jQuery in my project, I would use the second pattern as it is provided by the framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM