【发布时间】:2019-07-28 18:17:30
【问题描述】:
foo();
var a = true;
if (a) {
function foo() { console.log( "a" ); }
}
else {
function foo() { console.log( "b" ); }
}
我的预期输出是b,但是当我尝试在浏览器中运行时得到foo is not a function
【问题讨论】:
标签: javascript hoisting
foo();
var a = true;
if (a) {
function foo() { console.log( "a" ); }
}
else {
function foo() { console.log( "b" ); }
}
我的预期输出是b,但是当我尝试在浏览器中运行时得到foo is not a function
【问题讨论】:
标签: javascript hoisting
类似的一段代码在MDN Conditionally created functions中有解释
函数可以有条件地声明,也就是说,一个函数语句可以嵌套在一个 if 语句中,但是结果在不同的实现中是不一致的,因此这种模式不应该在生产代码中使用。对于条件函数创建,请改用函数表达式。
var hoisted = "foo" in this;
console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`);
if (false) {
function foo(){ return 1; }
}
// In Chrome:
// 'foo' name is hoisted. typeof foo is undefined
//
// In Firefox:
// 'foo' name is hoisted. typeof foo is undefined
//
// In Edge:
// 'foo' name is not hoisted. typeof foo is undefined
//
// In Safari:
// 'foo' name is hoisted. typeof foo is function
对于计算结果为 true 的条件,结果完全相同。
var hoisted = "foo" in this;
console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`);
if (true) {
function foo(){ return 1; }
}
// In Chrome:
// 'foo' name is hoisted. typeof foo is undefined
//
// In Firefox:
// 'foo' name is hoisted. typeof foo is undefined
//
// In Edge:
// 'foo' name is not hoisted. typeof foo is undefined
//
// In Safari:
// 'foo' name is hoisted. typeof foo is function
看起来您从You-Dont-Know-JS 系列丛书中获取了一段代码,作者也试图对此进行解释:
出现在普通块内的函数声明通常会提升到封闭范围,而不是像这段代码所暗示的那样是有条件的:...
[...代码...]
但是,请务必注意,这种行为并不可靠,并且可能会在 JavaScript 的未来版本中发生变化,因此最好避免在块中声明函数。
【讨论】:
you-don't know-js book 也应该是b @Arup Rakshit
在提升时它只是主变量声明,而不是值
【讨论】: