[英]Why the ES6 code and ES5 code has diffent result after compiling by Babel.js?
[英]Compiling ES6 arrow functions to Es5 using Babel.js
在查看有關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!
但是, Babel.js
將箭頭功能代碼轉換為ES5代碼,返回undefined
而不是Window
( 演示鏈接 )
"use strict"; setTimeout(function () { return undefined; }, 100);
"use strict"; setTimeout(function () { return this; }.bind(Window), 100);
如果我正在編寫ES6,我會期望Window
而不是undefined
這是一個錯誤嗎?
或者,我誤解了什么?
tl; dr: Babel假設每個文件都是一個模塊 。 模塊是嚴格的默認和他們的this
值是undefined
。
這包含在Babel FAQ中 :
Babel假設所有輸入代碼都是ES2015模塊。 ES2015模塊是隱含嚴格的模式,這意味着頂層
this
不是window
的瀏覽器也不是exports
的節點。如果您不想要此行為,則可以選擇禁用嚴格轉換器:
$ babel --blacklist strict script.js require("babel").transform("code", { blacklist: ["strict"] });
請注意:如果你這樣做,你願意偏離規范,這可能會導致未來的互操作問題。
有關詳細信息,請參閱嚴格的變換器文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.