问题描述
此代码
beforeEach(() => {
this.asd= '123';
this.sdf= '234';
this.dfg= '345';
this.fgh= '456';
});
已由Babel转换为:
has been transpiled by Babel to:
beforeEach(function() {
undefined.asd= '123';
undefined.sdf= '234';
undefined.dfg= '345';
undefined.fgh= '456';
});
为什么?
推荐答案
大概该代码位于模块的顶级范围内,因此它处于严格模式(模块的默认模式是严格模式),或者是以严格模式评估的文件(因为它具有use strict
或因为Babel的默认值。)
Presumably that code is at the top-level scope of a module, and so it's in strict mode (the default for modules is strict mode), or a file that is being evaluated in strict mode (because it has "use strict"
or because of Babel's defaults).
短版本:如果你期望此
由 beforeEach
决定,在调用你的回调时,你会想要使用函数
函数,不是箭头函数。继续阅读为什么Babel正在进行转换:
The short version: If you're expecting this
to be determined by beforeEach
when calling your callback, you'll want to use a function
function, not an arrow function. Read on for why Babel is transpiling as it is:
箭头函数的基本原理(除了简洁之外)是它们继承 this
从他们的上下文(就像他们关闭的变量),而不是由调用者设置它。在严格模式下,全局范围内的此
为 undefined
。所以Babel在编译时知道箭头函数中的这个
将是 undefined
并对其进行优化。
The fundamental thing about arrow functions (other than being concise) is that they inherit this
from their context (like a variable they close over), instead of having it set by the caller. In strict mode, this
at global scope is undefined
. So Babel knows, at compile-time, that this
within the arrow function will be undefined
and optimizes it.
你在评论中说过这是在另一个函数中,但我的猜测是它在另一个箭头函数里面,例如:
You've said in comments that this is inside another function, but my guess is that it's inside another arrow function, e.g.:
describe(() => {
beforeEach(() => {
this.asd= '123';
// ...
});
});
由于Babel知道此
是 undefined
在 describe
回调中,还知道这个
在 beforeEach
回调中是 undefined
。
Since Babel knows that this
is undefined
in the describe
callback, it also knows that this
is undefined
in the beforeEach
callback.
如果您将代码置于松散模式上下文中,或者在函数调用内部无法在编译时确定此
,则不会这样做。例如,在严格模式下,您的
If you put your code in a loose mode context, or inside a function call where this
can't be determined at compile-time, it won't do that. For example, in strict mode your
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
将被调用,因此这个
将被调用。
...because Babel doesn't know how foo
will be called, and thus what this
will be.
这篇关于Babel用undefined取而代之的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!