繁体   English   中英

为什么我的代码执行return语句后定义的函数?

[英]Why does my code execute a function defined after the return statement?

我有这段代码:

(function f(){
    function f(){ return 1; }
    return f();
    function f(){ return 2; }
 })();

为什么这段代码打印'2'?

函数声明被提升,因此在评估return语句之前处理它们。

第二个函数会覆盖第一个函数,因为它们具有相同的名称。

在javascript中,函数定义被提升到其包含函数的顶部。

您的功能由浏览器解释如下:

(function f(){
    //Functions defined first
    function f(){ return 1; }
    function f(){ return 2; } //<- Hoisted to top, now this is what f is

    //Now the rest of the code runs
    return f();

 })();

因为函数在return语句之前被提升和处理,所以你的最后一个函数f()返回2并覆盖第一个函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM