Javascript arrow function doesn't work as intended?

Viewed 523

The following code works as expected:

let letter = {
    getNum() {
        return this.number;
    }
};

let a = {number:20, __proto__:letter};

console.log(a.getNum()); // 20

but if getNum were changed to arrow function:

let letter = {
    getNum: () => this.number
};

a.getNum() returns undefined, why is that?

2 Answers

For regular functions, the value of this is (usually) determined when they are invoked.
For arrow functions, the value of this is determined when they are defined.

So for the first case, this is equal to a, because of the a in a.getNum(). But in the second case, the way you invoked it doesn't matter and this is probably equal to the window object (unless letter was created inside some other function). window.number is undefined.

Arrow functions do not have their own this value. this refers to enclosing context.

Related