Home >Web Front-end >JS Tutorial >Why Does `$(this)` Fail in jQuery Click Handlers with ES6 Arrow Functions?

Why Does `$(this)` Fail in jQuery Click Handlers with ES6 Arrow Functions?

DDD
DDDOriginal
2024-12-15 19:47:14149browse

Why Does `$(this)` Fail in jQuery Click Handlers with ES6 Arrow Functions?

ES6 Arrow Functions and jQuery $(this): Binding Confusion

ES6 arrow functions provide lexical this binding, simplifying code by eliminating the need for explicit bind() calls. However, when used with jQuery's click binding, this behavior can cause issues.

Unexpected Behavior with Arrow Functions:

Consider the following code:

class Game {
  foo() {
    this._pads.on('click', function() {
      if (this.go) { $(this).addClass('active'); }
    });
  }
}

By using an arrow function instead:

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

The $(this) reference is converted to an ES5-style closure (self = this).

Understanding ES6 Arrow Function Binding:

This behavior is inherent to ES6 arrow functions, and not a problem with Traceur translation. Arrow functions always bind this lexically to the enclosing context. In this case, the foo() method.

Solution Using event.currentTarget:

To resolve the issue, utilize event.currentTarget instead of $(this) to access the clicked element within the arrow function callback:

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

jQuery specifically provides event.currentTarget to accommodate situations where the callback function may not have access to the correct this context.

The above is the detailed content of Why Does `$(this)` Fail in jQuery Click Handlers with 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