推测该代码位于模块的顶级范围内,因此它处于严格模式(模块的默认值为严格模式),或者正在以严格模式评估的文件(因为它具有"use strict"或者因为 Babel 的默认值)。
简短版本:如果您希望在调用回调时 this 由 beforeEach 确定,则您需要使用 function 函数,而不是箭头函数。继续阅读为什么 Babel 会按原样进行转换:
箭头函数的基本特征(除了简洁之外)是它们从上下文继承this(就像它们关闭的变量一样),而不是由调用者设置。在严格模式下,全局范围内的this 是undefined。所以 Babel 在编译时知道箭头函数中的 this 将是 undefined 并对其进行优化。
您在 cmets 中说过这是在另一个函数中,但我猜它在另一个箭头函数中,例如:
describe(() => {
beforeEach(() => {
this.asd= '123';
// ...
});
});
由于 Babel 在describe 回调中知道this 是undefined,它也知道在beforeEach 回调中this 是undefined。
如果您将代码置于松散模式上下文中,或在无法在编译时确定 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 将是什么。