And then $(this) gets converted to ES5 (self = this) type closure.
Is a way to have Traceur ignore "$(this)" for lexical binding?
回答1:
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 () { }.
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.
The way to solve this particular problem is not to use this to gain access to the clicked element, but instead use event.currentTarget:
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.
回答2:
Event binding
$button.on('click',(e)=>{var $this = $(e.currentTarget);// ... deal with $this});
Loop
Array.prototype.forEach.call($items,(el, index, obj)=>{var $this = $(el);// ... deal with $this});
(This is an answer I wrote for another version of this question, before learning it was a duplicate of this question. I think the answer pulls together the information fairly clearly so I decided to add it as a community wiki, although it's largely just different phrasing of the other answers.)
You can't. That's half the point of arrow functions, they close over this instead of having their own that's set by how they're called. For the use case in the question, if you want this set by jQuery when calling the handler, the handler would need to be a function function.
But if you have a reason for using an arrow (perhaps you want to use this for what it means outside the arrow), you can use e.currentTarget instead of this if you like:
classGame{ foo(){this._pads.on('click', e =>{// Note the `e` argumentif(this.go){ $(e.currentTarget).addClass('active');// Using it}});}}
The currentTarget on the event object is the same as what jQuery sets this to when calling your handler.