【问题标题】:javascript function hoisting does not worksjavascript函数提升不起作用
【发布时间】:2016-06-22 03:49:28
【问题描述】:
function test(flag){
    if (flag) {
        return function test1(){console.log(1)}
    }else{
        return function test1(){console.log(2)}
    }
}
test(true)()
test()()

它记录 1 和 2,为什么不加倍 2? 这是怎么回事

我的英文不太好,谢谢

这也适用于 1 和 2

function test(flag){
    if (flag) {
        function test1(){console.log(1)}
        return test1
    }else{
        function test1(){console.log(2)}
        return test1
    }
}
test(true)()
test()()

【问题讨论】:

  • 那是因为在第一次调用中标志被传递为真,因此真正的块被执行,而在第二次调用中,标志将被传递为未定义,所以假块将被执行
  • 第一次调用时,flag 为真,然后执行if 条件。第二个flag为null,即为false,则执行else条件。
  • 不要这样写代码。

标签: javascript function hoisting


【解决方案1】:

这一行的函数:

return function test1(){console.log(2)}

不是函数声明。它是一个命名函数表达式,因为它是语句的一部分。

函数表达式不会被提升。只有函数声明被提升,像这样:

function test(){
    return test1;

    function test1() { console.log(1); }
    function test1() { console.log(2); }
}

test()();

编辑:关于您事后添加的问题,条件表达式中的函数声明具有未定义的行为,您可以根据您的 JavaScript 引擎看到不同的结果。 if-else 语句中的函数可能不会被提升到作用域的顶部,并且您不应该将函数声明放在条件表达式中。 More about this

【讨论】:

  • function test(flag){ if (flag) { function test1(){console.log(1)} return test1 }else{ function test1(){console.log(2)} return test1 } } test(true)() test()() 这也是 1 和 2
  • function test(flag){ if (flag) { function test1(){console.log(1)} return test1 }else{ function test1(){console.log(2)} return test1 } } test(true)() test()()
  • @user1861806 条件表达式中的函数声明具有未定义的行为,您可以根据您的 JavaScript 引擎看到不同的结果。在if-else 表达式中不能保证提升,您不应该将函数放在条件表达式中。
【解决方案2】:

在第一次调用test(true)() 时,它通过了:

if (flag) {
        return function test1(){console.log(1)}
    } 

因为flag 的值是true

在第二次调用test()() 中,它通过else 路径:

else{
        return function test1(){console.log(2)}
    }

因为在该实例中 flag 的值是未定义的,它的计算结果为 false

您可以通过这些链接了解truthyfalsy

希望您能理解这里的想法。如果您有任何问题,请告诉我。

【讨论】:

    猜你喜欢
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多