• 🏆 Texturing Contest #33 is OPEN! Contestants must re-texture a SD unit model found in-game (Warcraft 3 Classic), recreating the unit into a peaceful NPC version. 🔗Click here to enter!
  • It's time for the first HD Modeling Contest of 2024. Join the theme discussion for Hive's HD Modeling Contest #6! Click here to post your idea!

[Javascript] This

Status
Not open for further replies.

Chaosy

Tutorial Reviewer
Level 40
Joined
Jun 9, 2011
Messages
13,183
I've got a a piece of code which basically looks like:
Code:
class Name {

    someFunc() {
        console.log(this.x);
    }

    constructor() {
        this.x = 1;
        this.something.addEventListener("click", someFunc);
    }
}

Which writes undefined because "this" refers to "this.something" instead of the instance.

Are there any ways to work around that?
 
Level 29
Joined
Jul 29, 2007
Messages
5,174
There are two common ways to call back a method.

The first is to create a new instance of your method, bound to your this:
JavaScript:
this.something.addEventListener("click", someFunc.bind(this))// this.someFunc needed? not sure what class syntax sugar turns into
The first parameter to Function.prototype.bind is whatever you want this to be when the function is called.

The second way is to create a closure.

Assuming ES6, since you use the class keyword, you can use an arrow function:
JavaScript:
this.something.addEventListener("click", () => someFunc()) // this.someFunc() needed? not sure what class syntax sugar turns into
If for some reason you don't want an arrow function, use a regular closure:
JavaScript:
let self = this;
this.something.addEventListener("click", function () { self.someFunc(); }); // Anonymous closure, self is saved in its scope

Note that whichever way you write it, you will end up generating new functions.
This isn't ideal, but there isn't much to do in JS to avoid this.
It is something to take into consideration when you write callback-y code though (e.g. don't create a function in your main loop by mistake, etc.)
 
Last edited:
Status
Not open for further replies.
Top