【问题标题】:Hoisting of javascript with block statement [duplicate]用块语句提升javascript [重复]
【发布时间】: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


    【解决方案1】:

    类似的一段代码在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
    【解决方案2】:

    在提升时它只是主变量声明,而不是值

    【讨论】:

    • 函数声明除外,它也会提升函数值。
    • 是的,只在命名函数的情况下不在匿名函数中。
    猜你喜欢
    • 2021-01-04
    • 2013-02-25
    • 2014-05-17
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 2016-04-05
    相关资源
    最近更新 更多