javascript - Passing event listener a reference to "self"; - Stack Overflow

I just wanted to know if its acceptable to save a reference to "this" as a variable and then

I just wanted to know if its acceptable to save a reference to "this" as a variable and then use that in an eventListener. If not can someone please inform as to the best practice for passing reference to a different context in javascript.

Example:

someListener(){
    let self = this; //referencing this class
    
    someObject.addEventListener("click"), function(){
       //some magic applied here
       self.someArray.push("something");
    }
}

I cant think of another way to reference a different context (that of the class that the event listener belongs to) when dealing with an event.

Thanks

I just wanted to know if its acceptable to save a reference to "this" as a variable and then use that in an eventListener. If not can someone please inform as to the best practice for passing reference to a different context in javascript.

Example:

someListener(){
    let self = this; //referencing this class
    
    someObject.addEventListener("click"), function(){
       //some magic applied here
       self.someArray.push("something");
    }
}

I cant think of another way to reference a different context (that of the class that the event listener belongs to) when dealing with an event.

Thanks

Share Improve this question edited Jan 3, 2021 at 11:47 Paul Hashmi asked Jan 3, 2021 at 11:34 Paul HashmiPaul Hashmi 4667 silver badges20 bronze badges 2
  • If you pass the event listener an arrow function then self is not needed. – evolutionxbox Commented Jan 3, 2021 at 11:35
  • But this approach is also acceptable and widely used in pre-ES6 codes... – FZs Commented Jan 3, 2021 at 11:41
Add a ment  | 

2 Answers 2

Reset to default 4

That's fine, and highly idiomatic ES5 (using the name that is also mon).

ES6 gives us arrow functions which use a lexical this instead of having their own.

someListener(){
    someObject.addEventListener("click"), () => {
       //some magic applied here
       this.someArray.push("something");
    }
}

Before arrow functions were introduced, this was a mon way among javascript developers but now you can get around this problem using an arrow function

someListener(){
    someObject.addEventListener("click"), () => {
       this.someArray.push("something");
    }
}

Using an arrow function solves this problem because arrow functions do not get their own binding of this. They get their value from the enclosing scope, which in your case is the local scope of someListener function.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744729047a4590354.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信