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
Barbara StreisandOriginal
2024-12-13 10:11:17208browse

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

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!

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