【发布时间】:2015-08-22 12:43:48
【问题描述】:
在查看 Mozilla 文档中的 ES6 箭头函数文档时,我了解到箭头函数应用严格模式的所有规则,除了 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!
但是,Babel.js 将箭头函数代码转换为 ES5 代码,返回 undefined 而不是 Window(demo link)
"use strict";
setTimeout(function () {
return undefined;
}, 100);
所以,上面的 sn-p 是 Babel.js 的输出。不能是下面的输出吗?
"use strict";
setTimeout(function () {
return this;
}.bind(Window), 100);
如果我正在编写 ES6,我希望 Window 而不是 undefined
这是一个错误吗?
或者,我误解了什么?
【问题讨论】:
-
Babel 将所有内容置于严格模式。
undefined看起来正确。 -
@elclanrs 从 ES5 的角度来看是正确的,因为代码被转译为 ES5,但在 ES6 中的箭头函数的情况下,它应该是
window。 -
@dfsq 为什么应该是窗口?它将从未定义的封装对象继承
this;不是全球的。还是我想错了?
标签: javascript scope ecmascript-6 babeljs lexical-scope