Understanding Global & Local Scope in Javascript

后端 未结 2 1812
太阳男子
太阳男子 2020-12-03 18:00

I\'ve been learning Javascript using Object-Oriented JavaScript by Stoyan Stefanov

He offers an example comparing global and local scope:

var a = 123         


        
相关标签:
2条回答
  • 2020-12-03 18:44

    In simple words, all the declarations, of both variables and functions are considered first. So local var a in effect will override global variable only in local scope and will have no value i.e. undefined. So first alert will show undefined. Second alert will show 1 as it is after a = 1. This just happens locally and global variable a will have value 123 - it won't be changed.

    another example using function to show how it works

     function show(){
        alert("I am global");
     }
    
     function f() {
    
        show();
    
        show = function(){
           alert("I am second");
        }  
    
        show();   
    
        function show(){
            alert("I am first");
        }
    
    }
    f();
    show();
    
    0 讨论(0)
  • 2020-12-03 18:46

    It is not overriding the global variable. What is happening is called "variable hoisting". That is, a var a; gets inserted at the top of the function.

    The script engine changes your script to be the following:

    var a = 123;
    function f() {
        var a;
        alert(a);
        a = 1;
        alert(a);
    }
    f();
    

    Lesson to learn: Always declare your variables before you use them. Some will say declare all your variables at the top of the function.

    0 讨论(0)
提交回复
热议问题