哪种解决方案更适合通过“;这个“;javascript事件处理程序的参数

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

本文关键字:javascript 这个 程序 参数 事件处理 解决方案      更新时间:2023-09-26

将init函数的this参数传递给更改事件处理程序的最佳方法是什么?为什么?

选项1(使用that=this)。

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

选项2(使用事件数据)。

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

还是另一个(更好的)?

Imho第一个比较好。第三种方法(如果你可以使用ECMA5)是

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

如果您希望事件处理程序中的this引用"父函数"的this,您可以使用$.proxy[docs]:

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

但是,您必须访问event.currentTarget[docs]才能获得对事件处理程序绑定到的元素的引用。

除此之外,选择对你来说最有意义/你觉得最舒服的,并保持一致。

我倾向于将需要引用的函数包装在保存它的函数中,如下所示:

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

我不会说一种方法比另一种更好。只是如果我在项目中使用jQuery,我会使用框架提供的第二种模式。