Compiling ES6 arrow functions to Es5 using Babel.js

亡梦爱人 提交于 2019-12-12 11:00:29

问题




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?


回答1:


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.




回答2:


You are correct in principle, as described on MDN. However, Babel always places a 'use strict' at the root scope. 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.



来源:https://stackoverflow.com/questions/30702553/compiling-es6-arrow-functions-to-es5-using-babel-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!