Javascript function scoping and hoisting

后端 未结 18 2929
孤街浪徒
孤街浪徒 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:13

    Hoisting is a concept made for us to make it easier to understand. What actually happens is the declarations are done first with respect to their scopes and the assignments will happen after that(not at the same time).

    When the declarations happen, var a, then function b and inside that b scope, function a is declared.

    This function a will shadow the variable a coming from the global scope.

    After the declarations are done, the values assign will start, the global a will get the value 1 and the a inside function b will get 10. when you do alert(a), it will call the actual global scope variable. This little change to the code will make it more clear

            var a = 1;
    
        function b() {
            a = 10;
            return a;
    
            function a() { }
        }
    
        alert(b());
        alert(a);
    

提交回复
热议问题