Search code examples
javascriptarrow-functions

Javascript arrow function doesn't work as intended?


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?


Solution

  • 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.