使用 jQuery $(this) 和 ES6 箭头函数(词法 this 绑定) [英] Using jQuery $(this) with ES6 Arrow Functions (lexical this binding)

查看:38
本文介绍了使用 jQuery $(this) 和 ES6 箭头函数(词法 this 绑定)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用带有词法 this 绑定的 ES6 箭头函数很棒.

Using ES6 arrow functions with lexical this binding is great.

但是,我刚才在典型的 jQuery 单击绑定中使用它时遇到了一个问题:

However, I ran into an issue a moment ago using it with a typical jQuery click binding:

class Game {
  foo() {
    self = this;
    this._pads.on('click', function() {
      if (self.go) { $(this).addClass('active'); }
    });
  }
}

改用箭头函数:

class Game {
  foo() {
    this._pads.on('click', () => {
      if (this.go) { $(this).addClass('active'); }
    });
  }
}

然后 $(this) 被转换为 ES5 (self = this) 类型闭包.

And then $(this) gets converted to ES5 (self = this) type closure.

是一种让 Traceur 忽略词法绑定的$(this)"的方法吗?

Is a way to have Traceur ignore "$(this)" for lexical binding?

推荐答案

这与 Traceur 和关闭某些东西无关,这只是 ES6 的工作方式.这是您通过使用 => 而不是 function () { } 而要求的特定功能.

This has nothing to do with Traceur and turning something off, this is simply how ES6 works. It's the specific functionality you're asking for by using => instead of function () { }.

如果你想写ES6,你需要一直写ES6,你不能在某些代码行上切换进出,绝对不能压制或改变方式=> 有效.即使可以,您也会得到一些只有您理解的奇怪版本的 JavaScript,并且在您自定义的 Traceur 之外永远无法正常工作,这绝对不是 Traceur 的重点.

If you want to write ES6, you need to write ES6 all the time, you can't switch in and out of it on certain lines of code, and you definitely cannot suppress or alter the way => works. Even if you could, you would just wind up with some bizarre version of JavaScript that only you understand and which would never work correctly outside of your customized Traceur, which definitely isn't the point of Traceur.

解决这个特殊问题的方法不是使用this来访问被点击的元素,而是使用event.currentTarget:

The way to solve this particular problem is not to use this to gain access to the clicked element, but instead use event.currentTarget:

Class Game {
  foo(){
    this._pads.on('click', (event) => {
      if(this.go) {
        $(event.currentTarget).addClass('active');
      }
    });
  }
}

jQuery 提供 event.currentTarget 特别是因为,即使在 ES6 之前,jQuery 并不总是可以在回调函数上强加 this(即,如果它是通过 bind.

jQuery provides event.currentTarget specifically because, even before ES6, it is not always possible for jQuery to impose a this on the callback function (ie, if it was bound to another context via bind.

这篇关于使用 jQuery $(this) 和 ES6 箭头函数(词法 this 绑定)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆