简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM