Javascript function scoping and hoisting

后端 未结 18 2957
孤街浪徒
孤街浪徒 2020-11-21 04:20

I just read a great article about JavaScript Scoping and Hoisting by Ben Cherry in which he gives the following example:

var a = 1;

function b() {
    a =          


        
18条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 04:56

    Function hoisting means that functions are moved to the top of their scope. That is,

    function b() {  
       a = 10;  
       return;  
       function a() {} 
    } 
    

    will be rewritten by the interpeter to this

    function b() {
      function a() {}
      a = 10;
      return;
    }
    

    Weird, eh?

    Also, in this instance,

    function a() {}
    

    behaved the same as

    var a = function () {};
    

    So, in essence, this is what the code is doing:

    var a = 1;                 //defines "a" in global scope
    function b() {  
       var a = function () {}; //defines "a" in local scope 
       a = 10;                 //overwrites local variable "a"
       return;      
    }       
    b();       
    alert(a);                 //alerts global variable "a"
    

提交回复
热议问题