Home >Web Front-end >JS Tutorial >How to Correctly Use jQuery's $(this) with ES6 Arrow Functions in Event Handlers?
Using jQuery $(this) with ES6 Arrow Functions (lexical this binding)
Binding event handlers using ES6 arrow functions can be problematic when working with jQuery's $(this) selector. This is because arrow functions bind the this keyword lexically, which may not be the desired behavior in jQuery callbacks.
The following example illustrates the issue:
class Game { foo() { this._pads.on('click', () => { if (this.go) { $(this).addClass('active'); } }); } }
In the above example, using an arrow function for the click event handler results in $(this) referencing the Game instance instead of the clicked element. This is because arrow functions do not have their own this binding, so they inherit it from the surrounding scope.
Solution
To resolve this issue, avoid using arrow functions when binding jQuery event handlers. Instead, use traditional function declarations or bind the this keyword explicitly using the bind method:
class Game { foo() { this._pads.on('click', function() { if (this.go) { $(this).addClass('active'); } }.bind(this)); } }
Alternatively, you can access the clicked element using event.currentTarget:
class Game { foo() { this._pads.on('click', (event) => { if (this.go) { $(event.currentTarget).addClass('active'); } }); } }
Using event.currentTarget provides access to the element that triggered the event, regardless of the binding context of the callback function.
The above is the detailed content of How to Correctly Use jQuery's $(this) with ES6 Arrow Functions in Event Handlers?. For more information, please follow other related articles on the PHP Chinese website!