Using jQuery $(this) with ES6 Arrow Functions (lexical this binding)

前端 未结 5 695
一个人的身影
一个人的身影 2020-11-22 00:02

Using ES6 arrow functions with lexical this binding is great.

However, I ran into an issue a moment ago using it with a typical jQuery click binding:

5条回答
  •  半阙折子戏
    2020-11-22 00:23

    As Meager said in his answer on this same question If you want to write ES6, you need to write ES6 all the time,

    so if you are using arrow function of ES6: (event)=>{}, then you have to use $(event.currentTarget) instead of $(this).

    you can also use more nicer and cleaner way of using currentTarget as ({currentTarget})=>{},

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

    originally this idea was commented by rizzi frank in @Meager's answer, and i felt it useful and i think that not all people will read that comment so i have written it as this another answer.

提交回复
热议问题