Javascript function scoping and hoisting

后端 未结 18 2946
孤街浪徒
孤街浪徒 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 05:20

    Here's my recap of the answer with more annotation and an acompaniying fiddle to play around with.

    // hoisting_example.js
    
    // top of scope ie. global var a = 1
    var a = 1;
    
    // new scope due to js' functional (not block) level scope
    function b() {
        a = 10; // if the function 'a' didn't exist in this scope, global a = 10
      return; // the return illustrates that function 'a' is hoisted to top
      function a(){}; // 'a' will be hoisted to top as var a = function(){};
    }
    
    // exec 'b' and you would expect to see a = 10 in subsequent alert
    // but the interpreter acutally 'hoisted' the function 'a' within 'b' 
    // and in doing so, created a new named variable 'a' 
    // which is a function within b's scope
    b();
    
    // a will alert 1, see comment above
    alert(a);
    

    https://jsfiddle.net/adjavaherian/fffpxjx7/

提交回复
热议问题