简体   繁体   English

使用Babel.js将ES6箭头函数编译为Es5

[英]Compiling ES6 arrow functions to Es5 using Babel.js



While looking into ES6 arrow functions' documentation on Mozilla documentation, I got to know that Arrow functions applies all the rules of strict mode, except one as described in the link 在查看有关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! 

But, Babel.js is transpiling the arrow function code to ES5 code that returns undefined rather than Window ( demo link ) 但是, Babel.js将箭头功能代码转换为ES5代码,返回undefined而不是Window演示链接

 "use strict"; setTimeout(function () { return undefined; }, 100); 

So, the above snippet is the output from Babel.js. 所以,上面的代码片段是Babel.js的输出。 Couldn't it be the below output? 难道不是下面的输出?

 "use strict"; setTimeout(function () { return this; }.bind(Window), 100); 

If I am writing ES6, I would expect Window rather than undefined 如果我正在编写ES6,我会期望Window而不是undefined
Is it a bug? 这是一个错误吗?
OR, I misunderstood anything? 或者,我误解了什么?

tl;dr: Babel assumes every file is a module . tl; dr: Babel假设每个文件都是一个模块 Modules are strict by default and their this value is undefined . 模块是严格的默认和他们的this值是undefined


This is covered in the Babel FAQ : 这包含在Babel FAQ中

Babel assumes that all input code is an ES2015 module. Babel假设所有输入代码都是ES2015模块。 ES2015 modules are implicitly strict mode so this means that top-level this is not window in the browser nor is it exports in node. ES2015模块是隐含严格的模式,这意味着顶层this不是window的浏览器也不是exports的节点。

If you don't want this behaviour then you have the option of disabling the strict transformer: 如果您不想要此行为,则可以选择禁用严格转换器:

 $ babel --blacklist strict script.js require("babel").transform("code", { blacklist: ["strict"] }); 

PLEASE NOTE: If you do this you're willingly deviating from the spec and this may cause future interop issues. 请注意:如果你这样做,你愿意偏离规范,这可能会导致未来的互操作问题。

See the strict transformer docs for more info. 有关详细信息,请参阅严格的变换器文档

You are correct in principle, as described on MDN . 原则上你是正确的,如MDN所述 However, Babel always places a 'use strict' at the root scope. 但是,Babel总是在根范围内放置'use strict' In effect you compile the following: 实际上,您编译以下内容:

'use strict';
var f = () => { 'use strict'; return this};

In that case strict rules do apply. 在这种情况下,严格的规则适用。 See the compiled example here . 请参阅此处的编译示例。 Babel even optimizes away the top-level this as it is guaranteed to be undefined . Babel甚至会优化掉的顶层this ,因为它是保证undefined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM