Understanding Global & Local Scope in Javascript

后端 未结 2 1818
太阳男子
太阳男子 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: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.

提交回复
热议问题