define variable with/without var prefix 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

  • In global scope, there is no difference, unless you using it again: var my_var; will redeclare it, while my_var; will be simply useless expression.


    There is a difference only when not in global context.

    Ex1 (with var):

    var x = 0; 
    (function(){
      var x = 1; 
      alert('fx: '+ x);
    })(); 
    alert('gx: '+ x);
    
    //fx: 1
    //gx: 0
    

    Ex2 (without var):

    x = 0; 
    (function(){
      x = 1; 
      alert('fx: '+ x);
    })(); 
    alert('gx: '+ x);
    
    //fx: 1
    //gx: 1
    

    var is actually (re)declaring the variable in any current scope while second form is declaring it (globally?) unless it's been declared in a containing scope before. The second form is implicitly declaring, while first form is doing so explicitly.

    Thus there is no difference in global scope, for it isn't contained in any other scope.

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

    上一篇: 在Java 10中,什么类型的标记完全是“var”?

    下一篇: 在javascript中使用/不使用var前缀定义变量