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.js
is transpiling the arrow function code to ES5 code that returns undefined
rather than Window
(demo link)
"use strict";
setTimeout(function () {
return undefined;
}, 100);
"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?
Babel is a transpiler because it translates JavaScript ES6 to JavaScript ES5. In contrast, a compiler translates source code from a higher level language to a lower level.
The arrow function concept was introduced in ES6. With the help of this, we can write a shorter and concise syntax for a normal function which we used to write in ES5. Note: In arrow function, if there is only one statement then we don't even need to use '{}' curly braces.
BabelJS - ES5 There is extra code added using babeljs to get the functionality working for classes same as in ES5. BabelJs makes sure the functionality works same as it would have done in ES6.
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 notwindow
in the browser nor is itexports
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With