IT虾米网

javascript 函数提升不起作用

JustinYoung 2024年12月31日 程序员 24 0

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()() 

请您参考如下方法:

这一行的函数:

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


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!