問題描述
這段代碼
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).
簡短版本:如果您希望 this
在調用回調時由 beforeEach
確定,則您需要使用 function代碼>函數,而不是箭頭函數.繼續閱讀為什么 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
(就像它們關閉的變量一樣),而不是由調用者設置.在嚴格模式下,全局范圍內的 this
是 undefined
.所以 Babel 在編譯時知道箭頭函數中的 this
將是 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 在 describe
回調中知道 this
是 undefined
,它也知道 this
是 beforeEach
回調中的 undefined
.
Since Babel knows that this
is undefined
in the describe
callback, it also knows that this
is undefined
in the beforeEach
callback.
如果您將代碼置于松散模式上下文中,或在編譯時無法確定 this
的函數調用中,則不會這樣做.例如,在嚴格模式下你的
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
將如何被調用,因此 this
將是什么.
...because Babel doesn't know how foo
will be called, and thus what this
will be.
這篇關于Babel 將其替換為 undefined的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!