Home >Web Front-end >JS Tutorial >How to Correctly Use `$(this)` with jQuery Click Handlers and ES6 Arrow Functions?

How to Correctly Use `$(this)` with jQuery Click Handlers and ES6 Arrow Functions?

Linda Hamilton
Linda HamiltonOriginal
2024-12-07 22:11:12437browse

How to Correctly Use `$(this)` with jQuery Click Handlers and ES6 Arrow Functions?

jQuery $(this) and ES6 Arrow Functions

While ES6 arrow functions offer lexical this binding, they can pose a challenge when used with jQuery click bindings. When using arrow functions in this scenario, $(this) behaves differently, essentially emulating ES5 closure behavior:

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

To address this issue, it's important to understand that Traceur does not have the capability to ignore $(this) for lexical binding in this context. ES6 dictates the behavior of arrow functions, and they inherently lack access to lexical this.

The solution lies in using event.currentTarget instead of $(this):

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

jQuery provides event.currentTarget specifically for this purpose, as it recognizes that access to lexical this is not always feasible with callback functions. By leveraging event.currentTarget, the correct element will be targeted, avoiding the need to modify this binding or introduce dependency on ES5 code.

The above is the detailed content of How to Correctly Use `$(this)` with jQuery Click Handlers and ES6 Arrow Functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn