• Listen to a special audio message from Bill Roper to the Hive Workshop community (Bill is a former Vice President of Blizzard Entertainment, Producer, Designer, Musician, Voice Actor) 🔗Click here to hear his message!
  • Read Evilhog's interview with Gregory Alper, the original composer of the music for WarCraft: Orcs & Humans 🔗Click here to read the full interview.

[Javascript] This

Status
Not open for further replies.

Chaosy

Tutorial Reviewer
Level 41
Joined
Jun 9, 2011
Messages
13,239
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