Babel用undefined替换了这个



此代码

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

已经被巴别塔传送到:

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

为什么?

假设代码位于模块的顶层范围,因此它处于严格模式(模块的默认值为严格模式),或者是一个正在严格模式下评估的文件(因为它具有"use strict"或因为Babel的默认值)。

简短的版本:如果您希望this在调用回调时由beforeEach确定,那么您需要使用function函数,而不是箭头函数。继续阅读为什么巴别塔是transpiling原样:

箭头函数的基本功能(除了简洁之外)是,它们从上下文继承this(就像它们关闭的变量一样),而不是由调用方设置。在严格模式下,全局范围内的thisundefined。因此,Babel知道,在编译时,箭头函数中的this将是undefined,并对其进行了优化

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

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

由于Babel在describe回调中知道thisundefined,因此beforeEach回调中也知道thisundefined

如果您将代码放在松散模式上下文中,或者放在无法在编译时确定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';
  });
}

因为巴别尔不知道foo将如何被调用,也不知道this将是什么

我遇到了这个问题,把胖箭头函数改成了一个普通函数,它似乎又工作了。

() => {} 

更改为

function() {}

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

如果你对此不太熟悉,可以考虑阅读

  • MDN-本YDKJS
  • 这个&对象原型

最新更新