What does it mean global namespace would be polluted?

后端 未结 3 2054
萌比男神i
萌比男神i 2020-11-22 05:52

What does it mean global namespace would be polluted?

I don\'t really understand what global namespace getting polluted means.

3条回答
  •  深忆病人
    2020-11-22 06:27

    In JavaScript, declarations outside of a function are in the global scope. Consider this small example:

    var x = 10;
    function example() {
        console.log(x);
    }
    example(); //Will print 10
    

    In the example above, x is declared in the global scope. Any child scope, such as that created by the example function, effectively inherit things declared in any parent scopes (in this case, that's just the global scope).

    Any child scope that redeclares a variable declared in the global scope will shadow the global variable, potentially causing unwanted, hard to track bugs:

    var x = 10;
    function example() {
        var x = 20;
        console.log(x); //Prints 20
    }
    example();
    console.log(x); //Prints 10
    

    Global variables are usually not recommended because of the potential to cause problems like this. If we didn't use the var statement inside the example function, we would have accidentally overwritten the value of x in the global scope:

    var x = 10;
    function example() {
        x = 20; //Oops, no var statement
        console.log(x); //Prints 20
    }
    example();
    console.log(x); //Prints 20... oh dear
    

    If you want to read more and understand it properly, I suggest going through the ECMAScript specification. It may not be the most exciting of reads but it will help no end.

提交回复
热议问题