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

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

Take a test:


6条回答
  •  庸人自扰
    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
    

提交回复
热议问题