nodwj nodwj - 4 months ago 12
Node.js Question

Js inherited class instance undefined

I have a class which extends another class. But a function defined in the parent class that tries to reference "this", throws an exception stating "this" is undefined. Here is the relevant code:

class Entity {
constructor() {
this.axes = ['x', 'y'];
...

updatePosition() {
this.axes.forEach(function(axis) {
this.position[axis] += this.velocity[axis];
});
}
}

class Player extends Entity {
constructor() {
super();
....
}
...
}

var player = new Player();


And the error thrown:

.../player.js:25
this.position[axis] += this.velocity[axis];
^

TypeError: Cannot read property 'position' of undefined


Do you know why is the instance undefined, and how can I fix it?
Thanks!

Answer

In the context of forEach function this is global object not the player instance. Since you're using ES6 you could solve it by changing to arrow function like so:

updatePosition() {
    this.axes.forEach((axis) => {
        this.position[axis] += this.velocity[axis];
    });
}

Read more here, under "lexical this": https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions