Home > Web Front-end > JS Tutorial > Why Does `$(this)` Misbehave with jQuery and ES6 Arrow Functions?

Why Does `$(this)` Misbehave with jQuery and ES6 Arrow Functions?

Barbara Streisand
Release: 2024-12-13 10:11:17
Original
205 people have browsed it

Why Does `$(this)` Misbehave with jQuery and ES6 Arrow Functions?

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'); }
    });
  }
}
Copy after login

When an arrow function is used instead:

class Game {
  foo() {
    this._pads.on('click', () => {
      if (this.go) { $(this).addClass('active'); }
    });
  }
}
Copy after login

$(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'); }
    });
  }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template