简体   繁体   中英

Javascript functions parsing order

Can someone please explain in great detail why in the following function, the return value is 1.5? Does javascript parse bottom to top or there is more to it?

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

Functions are ' hoisted ' to the top of the scope they live in.

So your code actually reads:

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

QED:

(function f() {
    function f() { return 1; }
    return f();
    function f() { return 1.5; }
    function f() { return 2; }
})(); //=> 2

jsFiddle Demo

As a result of hoisting, this is equivalent to

(function f(){
 var f;
 f = function(){ return 1; };
 f = function(){ return 2; };
 f = function(){ return 1.5; };
 return f();
})();

Hoisting can be tricky, as there are two aspects of it occurring here. First, the variable definition is hoisted

Every definition of a variable is really a declaration of the variable at the top of its scope and an assignment at the place where the definition is. 1

Next, each function initialization is hoisted

Functions initializations happen at the top of the parent function (above vars). Since vars declarations with names already existent as a parameter or a function are no-ops, we get some surprising results. 1

1: Scope Cheatsheet MDN

when js interprer comes to the function first it looks for all var and function constructions (but not anonymous functions ) and atirs them in the order it has found them, after this it starts to execute code from start of the function. in your case f function which returns 1.5 is the last, so it pverides the previos 2 f functios

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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