mms*_*s27 20 javascript jasmine babeljs
这段代码
beforeEach(() => {
this.asd= '123';
this.sdf= '234';
this.dfg= '345';
this.fgh= '456';
});
Run Code Online (Sandbox Code Playgroud)
已被巴别塔描述为:
beforeEach(function() {
undefined.asd= '123';
undefined.sdf= '234';
undefined.dfg= '345';
undefined.fgh= '456';
});
Run Code Online (Sandbox Code Playgroud)
为什么?
T.J*_*der 26
据推测,代码位于模块的顶级范围,因此它处于严格模式(模块的默认模式是严格模式),或者是在严格模式下评估的文件(因为它具有"use strict"或者由于Babel的默认值) .
简短版本:如果您希望在调用回调时this确定beforeEach,则需要使用function函数,而不是箭头函数.请继续阅读为什么Babel正在进行转换:
关于箭头函数(除了简洁之外)的基本原理是它们this从它们的上下文继承(就像它们关闭的变量一样),而不是由调用者设置它.在严格模式下,this在全球范围内undefined.所以Babel在编译时知道,在this箭头函数中将会undefined优化它.
你在评论中说过这是在另一个函数中,但我的猜测是它在另一个箭头函数中,例如:
describe(() => {
beforeEach(() => {
this.asd= '123';
// ...
});
});
Run Code Online (Sandbox Code Playgroud)
由于巴贝尔知道this是undefined在describe回调中,它也知道this是undefined在beforeEach回调.
如果将代码置于松散模式上下文中,或者this在编译时无法确定的函数调用内,则不会这样做.例如,在严格模式下你的
beforeEach(() => {
this.asd= '123';
this.sdf= '234';
this.dfg= '345';
this.fgh= '456';
});
Run Code Online (Sandbox Code Playgroud)
的确确实如此
'use strict';
beforeEach(function () {
undefined.asd = '123';
undefined.sdf = '234';
undefined.dfg = '345';
undefined.fgh = '456';
});
Run Code Online (Sandbox Code Playgroud)
但是这个:
function foo() {
beforeEach(() => {
this.asd= '123';
this.sdf= '234';
this.dfg= '345';
this.fgh= '456';
});
}
Run Code Online (Sandbox Code Playgroud)
转向
'use strict';
function foo() {
var _this = this;
beforeEach(function () {
_this.asd = '123';
_this.sdf = '234';
_this.dfg = '345';
_this.fgh = '456';
});
}
Run Code Online (Sandbox Code Playgroud)
......因为巴贝尔不知道foo将如何被召唤,因此this将会是什么.
| 归档时间: |
|
| 查看次数: |
3780 次 |
| 最近记录: |