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

前端 未结 5 632
一个人的身影
一个人的身影 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:18

    (This is an answer I wrote for another version of this question, before learning it was a duplicate of this question. I think the answer pulls together the information fairly clearly so I decided to add it as a community wiki, although it's largely just different phrasing of the other answers.)

    You can't. That's half the point of arrow functions, they close over this instead of having their own that's set by how they're called. For the use case in the question, if you want this set by jQuery when calling the handler, the handler would need to be a function function.

    But if you have a reason for using an arrow (perhaps you want to use this for what it means outside the arrow), you can use e.currentTarget instead of this if you like:

    class Game {
      foo(){
        this._pads.on('click', e => {                   // Note the `e` argument
          if(this.go) {
            $(e.currentTarget).addClass('active');      // Using it
          }
        });
      }
    }
    

    The currentTarget on the event object is the same as what jQuery sets this to when calling your handler.

提交回复
热议问题