Safety of global vs local variables?

This question already has an answer here:

  • What is the scope of variables in JavaScript? 25 answers

  • No, the variable a in your function is not visible outside of the function scope. If you try to access the variable a somewhere else in the code it will display undefined , because you have just declared the variable, but didn't assign any value to it.

    Let's extend your example:

    var a;
    function myFunction() {
        var a = 4;
    }
    function anotherFunction() {
        console.log(a);
    }
    anotherFunction();
    > undefined
    

    When we called anotherFunction() it accessed the globaly declared a , it doesn't see the local variable a from myFunction . They are completely different.

    It is better not to use local variables in this way. If you need them, you better group them in one object, which would have the role of a namespace:

    var allMyLocalVariables = {
        a: 'a',
        b: 'b'
    }
    

    Now you can access them anywhere like this:

    console.log(allMyLocalVariables.a);
    

    and the probability that they will collide with other variables is very low if you chose a sensible and meaningfull name for your object/namespace.

    链接地址: http://www.djcxy.com/p/51674.html

    上一篇: JavaScript中的(function(){})()构造是什么?

    下一篇: 全局与局部变量的安全性?