用block语句吊起JavaScript

时间:2019-07-28 18:17:30

标签: 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

2 个答案:

答案 0 :(得分:3)

在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版本中发生变化,因此,最好避免在块中声明函数。

答案 1 :(得分:-1)

在吊装中,它只是主机变量声明,而不是值