使用Babel.js编译ES6箭头函数到Es5 [英] Compiling ES6 arrow functions to Es5 using Babel.js

查看:962
本文介绍了使用Babel.js编译ES6箭头函数到Es5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




在查看Mozilla文档中的ES6箭头函数文档时,我知道Arrow函数应用严格模式的所有规则,除了链接



  var f =()=> {'use strict';返回这个}; var g = function(){'use strict'; return this;} console.log(f()); //打印Window console.log(g()); // print undefined //我们可以在firefox中测试这个! 



但是, Babel.js 将箭头函数代码转换为返回 undefined 而不是窗口演示链接



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



所以上面的代码段是Babel.js的输出。不能是下面的输出吗?



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



如果我在写ES6, 窗口而不是未定义

这是一个错误?
或者,我误解了什么?

解决方案

tl; dr: Babel假定每个文件都是一个模块>。默认情况下,模块是严格,它们的这个值是 undefined






这在 Babel常见问题


Babel假定所有输入代码是ES2015模块。 ES2015模块是隐含的严格模式,所以这意味着浏览器中的顶级这个不是 window ,也不是 export 在节点中。



如果您不想要此行为,则可以选择禁用严格的变压器:

  $ babel --blacklist strict script.js 

require(babel)。transform code,{blacklist:[strict]});

请注意:如果你这样做,你会放心地偏离规范,这可能会导致未来的互操作 b

docs 获取更多信息。





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

  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.jsis transpiling the arrow function code to ES5 code that returns undefined rather than Window(demo link)

"use strict";

setTimeout(function () {
  return undefined;
}, 100);


So, the above snippet is the output from 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
Is it a bug?
OR, I misunderstood anything?

解决方案

tl;dr: Babel assumes every file is a module. Modules are strict by default and their this value is undefined.


This is covered in the Babel FAQ:

Babel assumes that all input code is an ES2015 module. 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.

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.

这篇关于使用Babel.js编译ES6箭头函数到Es5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆