Using jQuery $(this) with ES6 Arrow Functions: Lexical This Binding
When using jQuery's $(this) with ES6 arrow functions, developers may encounter an issue where $(this) is converted to an ES5-style closure using self = this. This behavior is due to the lexical binding nature of arrow functions.
Issue:
The following code demonstrates the problem:
class Game { foo() { self = this; this._pads.on('click', function() { if (self.go) { $(this).addClass('active'); } }); } }
When an arrow function is used instead:
class Game { foo() { this._pads.on('click', () => { if (this.go) { $(this).addClass('active'); } }); } }
$(this) is converted to an ES5-style closure, leading to unexpected behavior.
Solution:
This issue is an inherent characteristic of ES6 arrow functions, and cannot be bypassed using Traceur. To resolve this, one must avoid using this to access the clicked element. Instead, the event.currentTarget property can be used:
class Game { foo() { this._pads.on('click', (event) => { if (this.go) { $(event.currentTarget).addClass('active'); } }); } }
jQuery specifically provides event.currentTarget for situations where the this binding may be ambiguous due to external factors, such as the callback function being bound to another context via .bind().
The above is the detailed content of Why Does `$(this)` Misbehave with jQuery and ES6 Arrow Functions?. For more information, please follow other related articles on the PHP Chinese website!