Nav*_*eth 5 javascript scope lexical-scope ecmascript-6 babeljs
在查看有关Mozilla文档的ES6 arrow函数文档时,我知道Arrow函数应用了严格模式的所有规则,除了链接中描述的那些规则
var f = () => { 'use strict'; return this};
var g = function () { 'use strict'; return this;}
console.log(f()); //prints Window
console.log(g()); // prints undefined
//we can test this in firefox!Run Code Online (Sandbox Code Playgroud)
但是,Babel.js将箭头功能代码转换为ES5代码返回undefined而不是Window(演示链接)
"use strict";
setTimeout(function () {
return undefined;
}, 100);Run Code Online (Sandbox Code Playgroud)
"use strict";
setTimeout(function () {
return this;
}.bind(Window), 100);Run Code Online (Sandbox Code Playgroud)
如果我正在编写ES6,我会期待Window而不是undefined
它是一个错误吗?
或者,我误解了什么?
tl; dr: Babel假设每个文件都是一个模块.模块默认是严格的,它们的this值是undefined.
这包含在Babel FAQ中:
Babel假设所有输入代码都是ES2015模块.ES2015模块是隐式严格模式,因此这意味着顶层
this不在window浏览器中,也不exports在节点中.如果您不想要此行为,则可以选择禁用严格转换器:
Run Code Online (Sandbox Code Playgroud)$ babel --blacklist strict script.js require("babel").transform("code", { blacklist: ["strict"] });请注意:如果你这样做,你愿意偏离规范,这可能会导致未来的互操作问题.
有关详细信息,请参阅严格的变换器文档.
| 归档时间: |
|
| 查看次数: |
1927 次 |
| 最近记录: |