【发布时间】:2019-02-21 04:43:51
【问题描述】:
这是一个例子:
function b() {
console.log(f);
{
function f() {}
}
}
b()
我以为会变成:
function b() {
// hoist to function scope
function f() {}
console.log(f); // should output function f
}
或
function b() {
console.log(f); // should output reference error
{
// just hoist to block scope like this
function f() {}
}
}
但它输出未定义,例如 var 提升。为什么?
【问题讨论】:
-
在 ES2015 之前不允许函数声明,但浏览器仍然支持它,但每个浏览器的做法不同。 ES2015 在附录中描述了这种行为:ecma-international.org/ecma-262/6.0/…。根据上下文(非严格与严格),函数声明基本上被评估为分配函数表达式的变量声明。在严格模式下,此代码会引发错误。
标签: javascript function ecmascript-6 scope hoisting