which and how javascript function will be called if we have 2 function declarations with the same name?

前端 未结 6 1446
旧巷少年郎
旧巷少年郎 2021-01-14 04:58

Take a test:


相关标签:
6条回答
  • 2021-01-14 05:20

    It's because the latter function overwrites the previous one. If you try to log the function:

    console.log(say);
    

    It will return only:

    function say() { alert( "BELOW" ); } 
    

    The "ABOVE" alert has been replaced with the "BELOW" alert. Similar to declaring a variable with the same name twice in the same scope - the latter would overwrite the former.

    JSFiddle example.

    Why? See http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

    0 讨论(0)
  • 2021-01-14 05:24

    In this case the interpreter parses the function definitions first and the last function definition wins.

    This question has also been answered at: Ambiguous function declaration in Javascript

    There is also a good article here: http://kangax.github.com/nfe/

    0 讨论(0)
  • 2021-01-14 05:27

    function xyz() { .. } blocks are defined at parse time. If many functions have the same name, it's the last defined which takes the precedence.


    However, you can define functions at runtime using statements :

    var say = function() { alert( "ABOVE" ); }
    say(); 
    say = function() { alert( "BELOW" ); }
    

    will output ABOVE. (JSFiddle)

    0 讨论(0)
  • Basically, because of hoisting, which pulls all function declarations to the top of the current scope, the interpreter is basically doing this:

    function say() { alert( "ABOVE" ); }
    function say() { alert( "BELOW" ); }
    say();
    

    That is why it always ends up alerting below

    0 讨论(0)
  • 2021-01-14 05:34

    The interpreter first reads all declarations of the functions, then executes the other statements that are outside functions. So the latter declaration overrides the former, which is why the latter was called.

    0 讨论(0)
  • 2021-01-14 05:45
    (function () {
    
    // even though not declared yet, every 'inner' function will be hoisted,
    // and be available to the entire function
    sing();
    
    // variables are dealt with after functions, so say will be a string
    // the order of declaration suggests this to be the case, but that isn't what matters
    function say () { }
    
    var say = "say";
    
    // variables are dealt with after functions, so shout will be a string
    // even though the order suggests shout should be a function
    var shout = "shout";
    
    function shout() { }
    
    // both are functions, the latter one 'wins'
    function sing() { console.log("sing1"); }
    
    function sing() { console.log("sing2"); }
    
    console.log(typeof say, typeof shout);
    
    sing();
    
    }())
    

    Output:

    sing2
    string string
    sing2
    
    0 讨论(0)
提交回复
热议问题