Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
哪种解决方案更适合通行证;这";javascript事件处理程序的参数_Javascript_Jquery - Fatal编程技术网

哪种解决方案更适合通行证;这";javascript事件处理程序的参数

哪种解决方案更适合通行证;这";javascript事件处理程序的参数,javascript,jquery,Javascript,Jquery,将init函数的this参数传递给变更事件处理程序的最佳方法是什么?为什么 选项1(使用该选项=此选项) 备选案文2(使用) 还是另一种(更好的)方法?我不会说一种方法比另一种好。只是如果我在我的项目中使用jQuery,我会使用框架提供的第二种模式。Imho第一种模式更好一些。第三种方法(如果可以使用ECMA5)是 如果希望事件处理程序中的this引用“父函数”的this,可以使用: 但是,您必须访问以获取对事件处理程序绑定到的元素的引用 除此之外,选择对您/您觉得最合适的,并且保持一致的函数。

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

选项1(使用该选项=此选项)

备选案文2(使用)


还是另一种(更好的)方法?

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

Imho第一种模式更好一些。第三种方法(如果可以使用ECMA5)是


如果希望事件处理程序中的
this
引用“父函数”的
this
,可以使用:

但是,您必须访问以获取对事件处理程序绑定到的元素的引用


除此之外,选择对您/您觉得最合适的,并且保持一致的函数。

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

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

+第一种方法是1。解释是,第一个选项(闭包)不会使event.data对象混乱,因为将来可能需要在event.data对象中添加其他对象。所有答案都很好地概括了各种可能性。我想我会选择第一个选项,因为这对我来说是最干净的一个,因此请将此作为答案。谢谢。@MartijnB:这和
$一样。proxy
正在做的事情。我假设它在内部使用
.bind
(如果可用)。为了获得最佳兼容性,您应该使用
$.proxy
(我不想贬低这个答案,只想指出它)。这是我的标准方法。“this”应该指向OO编程中的实例,这样可以在不做额外工作的情况下保持模式。
SomeObject.prototype.init = function () {

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

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