使用 $.proxy 同时仍然可以访问原来的 this

Using $.proxy while still having access to what would be the original this

有没有办法代理 "this" 但仍然可以访问您现在所在上下文的 "this"?我通常将 this 设置为 self 但我很好奇在使用 $.proxy.

时是否有办法拥有两个上下文

例如...

$('.something').on('click', $proxy(function() {
  // this = proxied this
  // $(this) needs to equal .something
}, this));

显然this不能神奇地引用两个不同的值。

您不一定非要绑定外层 this,还有其他方法可以访问它的值:How to access the correct `this` context inside a callback?.

如果您想使用 $.proxy,您可以使用 event.currentTarget 访问元素(通常由 this 引用):

$('.something').on('click', $proxy(function(event) {
    $(event.currentTarget).whatever()
}, this));

不幸的是,如果没有包装函数,您将无法做到这一点。但为什么不将外部 this 保存在外部,然后在函数内部使用呢?

var self = this;
$('.something').on('click', function() {
    self.doSomething();
    // this == element
});

此外,在那种情况下,由于您处于事件处理程序中,因此您可以访问  event 对象内的元素,因为 this === event.currentTarget。所以你可以使用这样的东西:

$('.something').on('click', $proxy(function(e) {
  // this = proxied this
  // $(e.currentTarget) equal to .something
}, this));