jQuery 多个回调 "this" 参考

jQuery Multiple Callbacks "this" reference

我正在努力通过配置对象输入的事件回调函数向 jQuery 组件添加一些功能更改。

我真的很想将每个功能更改分成它自己的一组功能。

我想知道如何最好地处理 "this" 引用。由于我想将多个函数附加到每个回调,我假设我需要为每个调用其他选项的匿名函数。我会简单地将 "this" 引用作为参数传递给我的函数,还是有更好的方法来做到这一点?

function somePluginAfterSelectFeatureOne(this, param ){
  // do stuff
}

function somePluginAfterSelectFeatureTwo(this, param){
  // do stuff
}

$('.some-element').somePlugin({
  afterSelect: function(param){
     somePluginAfterSelectFeatureOne(this, param);
  }
});

是的,我会推荐 "apply" 或闭包 - 我不确定性能如何..我几乎不记得闭包比绑定更好的原因 "this",但我不知道相信您想要哪一个真的很重要。闭包并不总是有意义,因为它与应用程序的 architecture/design 紧密相关。

首先 - 我永远不会将 "this" 作为函数的参数传递,javascript 知道更好的方法来实现这一点:

function somePluginAfterSelectFeatureOne(param ){
  // do stuff
}

function somePluginAfterSelectFeatureTwo(param){
  // do stuff
}

$('.some-element').somePlugin({
  afterSelect: function(param){
     somePluginAfterSelectFeatureOne(param);
  }
});

首先,从你的函数参数中删除 "this" 作为参数,这是错误的 ;)

现在调用 "somePluginAfterSelectFeatureOne(param)" 将失败,因为 this 是什么?那么 "this" 将导致在您定义函数时有效的范围(很难解释,请尝试调试它;))

无论如何 - 要控制函数的 "this",您只需重写调用:

somePluginAfterSelectFeatureOne.apply(this, [param]);

现在,我想您的 "afterSelect: function(param){ }" 调用中已经可用的 "this" 应该是正确的,对吧?因此,通过使用本机函数 "apply",您可以将新的 "this" 传递给被调用函数,并且您仍然可以传递所有普通参数 -> 这只是第二个参数"apply"。但请注意,当使用 apply -> 时,所有参数都必须作为数组传递(因为内部 "arguments" 参数 always 可用于每个函数调用,实际上是一个内部数组)

现在,这仍然是直接绑定的解决方案 - 闭包仍然是一个不同的游戏:

$('.some-element').somePlugin({
  afterSelect: function(param){
     var _self = this,
         myFunction = function(param) {
             _self.anotherFn(param)
         };

     myFunction(param);         
  }
});

如您所见——我们只是将 "this" 存储为一个名为“_self”的局部变量。现在,如果函数定义在与上面相同的范围内 -> “_self”将可用它,即使没有通过它(这就是我们所说的 "closure" ;))。

但是您也可以看到 - 它并不总是有意义...在您的示例中,您将被迫将函数定义移动到 "afterSelect" 函数中,这完全不是目标在这里。

所以,我会采用 "apply" 模式并很好地传递 "this" - 有点像 "delegate" ;)

哦,做一个完整的综述——也可以直接在函数定义级别覆盖 "this"。为此使用 "bind":

function myFunction(param) {
    this.secondFunction(param)
}.bind(somethingDifferentWhichWillBeUsedAsThisInside)

我在这里还获得了关于这两个主题的一些一直以来最喜欢的话题:

  • What is the scope of variables in JavaScript?
  • How does the "this" keyword work?
  • How do JavaScript closures work?

this 不是有效的参数名称。将其更改为 element 并将其传递给您的自定义函数。

我不喜欢使用 this 除非它在原型方法(或构造函数)中。

function somePluginAfterSelectFeatureOne(element, param ){
  // `element` is what you wanted `this` to be 
}

$('.some-element').somePlugin({
  afterSelect: function(param){
     somePluginAfterSelectFeatureOne(this, param);
  }
});

如果你真的想使用this,你可以使用Function.prototype.call

function somePluginAfterSelectFeatureOne(param ){
    console.log(this); // The element that the event fired on 
}

$('.some-element').somePlugin({
  afterSelect: function(param){
     somePluginAfterSelectFeatureOne.call(this, param);
  }
});