Babel 将其替换为 undefined

Babel replaces this with undefined

这个代码

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

已被 Babel 转译为:

beforeEach(function() {
        undefined.asd= '123';
        undefined.sdf= '234';
        undefined.dfg= '345';
        undefined.fgh= '456';
});

为什么?

大概代码在模块的顶级范围内,因此它处于严格模式(模块的默认模式是严格模式),或者正在以严格模式评估的文件(因为它有 "use strict" 或者因为 Babel 的默认值)。

简短版本:如果您希望 this 在调用回调时由 beforeEach 确定,您需要使用 function 函数,而不是箭头功能。继续阅读为什么 Babel 会按原样进行转译:

箭头函数的基本原理(除了简洁之外)是它们从它们的上下文中继承 this(就像它们关闭的变量),而不是由调用者设置它。在严格模式下,全局范围内的 thisundefined。所以 Babel 知道,在编译时,箭头函数中的 this 将是 undefined 并优化它。

你在评论中说这是在另一个函数中,但我的猜测是它在另一个箭头函数中,例如:

describe(() => {
    beforeEach(() => {
        this.asd= '123';
        // ...
    });
});

因为 Babel 在 describe 回调中知道 thisundefined,它 知道 thisundefinedbeforeEach 回调中。

如果您将代码放在松散模式上下文中,或者放在 this 无法在编译时确定的函数调用中,它不会这样做。例如,在严格模式下你的

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

确实可以转换为

'use strict';
beforeEach(function () {
  undefined.asd = '123';
  undefined.sdf = '234';
  undefined.dfg = '345';
  undefined.fgh = '456';
});

但是这个:

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

转译为

'use strict';

function foo() {
  var _this = this;

  beforeEach(function () {
    _this.asd = '123';
    _this.sdf = '234';
    _this.dfg = '345';
    _this.fgh = '456';
  });
}

...因为 Babel 不知道 foo 将如何被调用,因此 this 将是什么。

我遇到了这个问题,把我的粗箭头函数改成了一个普通函数,它似乎又能用了。

() => {} 

改为

function() {}

箭头函数没有自己的 this 或参数绑定。相反,这些标识符像任何其他变量一样在词法范围内解析。这意味着在箭头函数内部,this 和参数指的是 this 的值和箭头函数定义环境中的参数(即 "outside" 箭头函数)。
在您的场景中,全局范围内的 this 未定义。在编译时,babel 会将箭头函数中的 this 转译为 undefined.

如果您对此不是很熟悉,请考虑阅读