When to use var in Javascript

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

  • When you use var , you are instantiating a variable in the current scope. This will also prevent access of variables named the same in higher scope, within the current scope.

    In your first example, 'a' is being instantiated and set within the function scope. In your second example, 'a' is being set outside the function scope due to lack of var

    With var :

    var a = "A"
    (function(){
      var a = "B"
      alert(a) //B
    })()
    
    alert(a); //A
    

    Without var :

    var a = "A";
    (function(){
      a = "B"
      alert(a) //B
    })()
    
    alert(a) //B
    

    Using var:

    var a = 'world';   
    myfunction = function(){
      var a = "mundo"
      alert("Hola, " + a )
    }
    
    myfunction();  //alerts 'hola, mundo'
    alert(a);  //alerts 'world';
    

    Not using var:

    var a = 'world';   
    myfunction = function(){
      a = "mundo"
      alert("Hola, " + a )
    }
    
    myfunction();  //alerts 'hola, mundo'
    alert(a);  //alerts 'mundo'
    

    I think that you need to refresh yourself on Javascript object scopes.

    Using the "var" keyword will place your variable at the top-most (global) scope. This means that if a function uses the same variable, the "var" variable you declared will overwrite the (non-var) variable in your function... JavaScript Scopes

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

    上一篇: js中的“var”需要什么时候?

    下一篇: 何时在Javascript中使用var