简体   繁体   English

Javascript中的递归异常行为

[英]Recursion in Javascript strange behavior

I'm struggling to find the answer to this question why does this code: 我正在努力找到这个问题的答案,为什么这样的代码:

    (function h(){
        var x = 1;
        return x;
        x = 2;
    })();

Returns 1, when this code: 此代码返回1:

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

Returns 2 返回2

I've debugged it and in both cases in never goes past return g() or return x part. 我已经调试了它,并且在两种情况下都不会超过返回g()或返回x部分。 The recursion part in function g, should call function g() with the first implementation of it in which it returns 1. 函数g的递归部分应在函数g()的第一个实现中调用它,该函数返回1。

This is because Javascript hoists (brings to the top) any function definition. 这是因为Javascript提升(带到顶部)任何函数定义。 The interpreter re-orders your outer function as: 解释器将您的外部函数重新排序为:

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

The second g() overrides the first one, and so outer function returns the result of executing that second g(), which is 2. 第二个g()覆盖第一个g(),因此外部函数返回执行第二个g()的结果。

More about hoisting can be found here 有关起重的更多信息,请点击此处

To get the result you were expecting, you can assign the functions as vars instead, this will not hoist them: 为了获得您期望的结果,您可以将这些函数分配为var,这不会使它们升降:

(function g(){
    var g = function(){ return 1; }
    return g();
    g = function(){ return 2; }
})()

That is called Hoisting : 这就是所谓的吊装

Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function). 提升是JavaScript的默认行为,即将所有声明移到当前作用域的顶部(当前脚本或当前函数的顶部)。

You should be careful with this and, by extension, with any magic that JS does when it tries to help you because you weren't disciplined. 您应该小心这一点,并扩展一下,因为您没有纪律,所以JS在尝试帮助您时会做的任何魔术都应小心。

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

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