使用jQuery $(this)与ES6箭头函数(词法这个绑定) [英] Using jQuery $(this) with ES6 Arrow Functions (lexical this binding)
问题描述
但是,我遇到了一个问题,之前使用它与典型的jQuery点击绑定:
类游戏{
foo(){
自我=这个
this._pads.on('click',function(){
if(self.go){$(this).addClass('active');}
});
}
}
使用箭头函数:
class Game {
foo(){
this._pads.on('click',()=> {
if(this.go){$(this).addClass('active');}
});
}
}
然后 $ )
被转换为ES5(self = this)类型闭包。
是否让Traceur忽略$(this)用于词法绑定?
这与Traceur无关,并关闭一些东西。这是ES6的工作原理,这是您使用 =>
要求的具体功能。如果你想写ES6,你需要一直写ES6,你不能选择退出它在某些代码行。即使可以,您也可以使用只有您了解的一些混合版本的JavaScript,这在您的定制Traceur之外将无法正常工作,这不是Traceur的重点。
解决这个问题的方法是不要使用这个
来访问点击的元素。使用 event.currentTarget
:
类游戏{
foo (){
this._pads.on('click',(event)=> {
if(this.go){$(event.currentTarget).addClass('active');}
});
}
}
Using ES6 arrow functions with lexical this
binding is great.
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'); }
});
}
}
Using an arrow function instead:
class Game {
foo() {
this._pads.on('click', () => {
if (this.go) { $(this).addClass('active'); }
});
}
}
And then $(this)
gets converted to ES5 (self = this) type closure.
Is a way to have Traceur ignore "$(this)" for lexical binding?
This has nothing to do with Traceur and turning something off. This is how ES6 works, it's the specific functionality you're asking for by using =>
. If you want to write ES6, you need to write ES6 all the time, you can't opt out of it on certain lines of code. Even if you could, you would just wind up with some bastardized version of JavaScript that only you understand, which would never work correctly outside of your customized Traceur, which isn't the point of Traceur.
The way to solve this is not to use this
to gain access to the clicked element. Use event.currentTarget
:
Class Game {
foo(){
this._pads.on('click', (event) => {
if(this.go) { $(event.currentTarget).addClass('active'); }
});
}
}
这篇关于使用jQuery $(this)与ES6箭头函数(词法这个绑定)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!