在查看 Mozilla 文档上的 ES6 箭头函数文档时,我了解到箭头函数应用了严格模式的所有规则,除了在link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Relation_with_strict_mode
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
正在将箭头函数代码转换为返回的 ES5 代码undefined
而不是Window
()
"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);
如果我写 ES6,我会期望Window
而不是undefined
这是一个错误吗?
或者,我误解了什么?
tl;dr:Babel 假设每个文件都是module。模块是strict默认情况下和他们的this
值为undefined
.
这包含在巴别塔常见问题解答 http://babeljs.io/docs/faq/#why-is-this-being-remapped-to-undefined-:
Babel 假设所有输入代码都是 ES2015 模块。 ES2015 模块是隐式严格模式,因此这意味着顶层this
is not window
在浏览器中也不是exports
在节点中。
如果您不希望出现这种行为,则可以选择禁用严格转换器:
$ babel --blacklist strict script.js
require("babel").transform("code", { blacklist: ["strict"] });
请注意:如果您这样做,您将自愿偏离规范,这可能会导致未来的互操作问题。
See the 严格的变压器文档 http://babeljs.io/docs/advanced/transformers/other/strict了解更多信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)