Babel replaces this with undefined

前端 未结 3 1693
[愿得一人]
[愿得一人] 2021-02-18 15:47

This code

beforeEach(() => {
        this.asd= \'123\';
        this.sdf= \'234\';
        this.dfg= \'345\';
        this.fgh= \'456\';
});

3条回答
  •  -上瘾入骨i
    2021-02-18 16:12

    Arrow functions don't have their own this or arguments binding. Instead, those identifiers are resolved in the lexical scope like any other variable. That means that inside an arrow function, this and arguments refer to the values of this and arguments in the environment the arrow function is defined in (i.e. "outside" the arrow function).
    In your scenario, this at global scope is undefined. At compile-time, babel will transpile this within the arrow function as undefined.

    If you are not very familiar with this, consider reading

    • MDN - this YDKJS
    • this & Object prototypes

提交回复
热议问题