What happens when JavaScript variable name and function name is the same?

前端 未结 5 907
南方客
南方客 2020-11-29 03:45

I have the following code, where I declare a function and after it, a variable with the same name as the function:

function a(x) {
    return x * 2;
}

var a         


        
5条回答
  •  感动是毒
    2020-11-29 04:17

    You should also remember that var a is hoisted, which makes it more like this

    var a; // placed
    
    function a(x) {
      return x * 2;
    };
    
    var a; // removed
    alert (a); // a is replaced by function body
    

    Remember that var a is hoisted, so if you assign 4 to a:

    var a; // placed
    
    function a(x) {
      return x * 2;
    };
    
    var a = 4; // removed
    a = 4 // added
    
    alert (a); // a is now 4
    

提交回复
热议问题