Difference between javascript variable with var and without var?

This question already has an answer here:

  • What is the purpose of the var keyword and when should I use it (or omit it)? 18 answers

  • If you declare a variable with "var" within a function will be local to your function, else the js engine will start to look for the variable in the local scope (function) and if doesn't find it then will be declared in the globalspace automatically

    From this link: https://www.inkling.com/read/javascript-definitive-guide-david-flanagan-6th/chapter-3/variable-scope

    When you declare a global JavaScript variable, what you are actually doing is defining a property of the global object (The Global Object). If you use var to declare the variable, the property that is created is nonconfigurable (see Property Attributes), which means that it cannot be deleted with the delete operator.

    Then if you do within a function or in the global-space (outside any function):

    temp=10;

    You could use it anywhere like:

    console.log(window.temp);

    Just a bunch of nested functions ( read the code comments starting from the inner one for better understanding):

    //lots of stuff here but not a "var temp=9"
    
    //I couldn't find "x" I will make it global as a property of the globalObject
     function myFunction(){ //is x here ? no ? then look outside
        (function(){ //is x here ? no ? then look outside
            (function() {  //is x here ? no ? then look outside
                    x=5; //declaring x without var, I will look for it
            }());
        }());
    }
    
    myFunction();
    console.log(window.x); //As x was declared a property from the global object I can do this.
    

    If you declare it with var within a function you can't do window.temp also if you do it inside a function that variable will be "local" to your funciton, ie:

    foo = 1;
    function test() {
        var foo = 'bar';
    }
    test();
    alert(foo);
    
    // Result: 1
    

    Source here from above sample and others here

    Also notice that using "var" in the global-space (outside) all your functions will create a global variable (a property in the window object) btw, use var always.


    When you define the variable at the global scope, then you can access it anywhere. If you redefine it using it var, then the variable has that value only in the current scope.

    Define a variable in the global scope:

    var a = 1;
    

    Now you can access it via a function's scope like this:

    function print() {
      console.log(window.a); // 1
      window.a = 5;
      anotherFunction(); // 5 
      var a = 3;
      console.log(a); // 3
    }
    function anotherFunction() {
      console.log(a); // 5;
    }
    
    链接地址: http://www.djcxy.com/p/17356.html

    上一篇: 在javascript程序中何处使用“var”

    下一篇: javascript变量与var和不var之间的区别?