Javascript var关键字的用途是什么?我应该在什么时候使用它(或省略它)?

Javascript var关键字的用途是什么?我应该在什么时候使用它(或省略它)?,javascript,keyword,ecmascript-5,Javascript,Keyword,Ecmascript 5,注意:这个问题是从ECMAScript版本3或5的角度提出的。随着ECMAScript 6版本中新功能的引入,答案可能会过时 JavaScript中var关键字的功能到底是什么,它们之间的区别是什么 var someNumber = 2; var someFunction = function() { doSomething; } var someObject = { } var someObject.someProperty = 5; 及 ? 你什么时候会使用其中一个,为什么/它做什么?如果

注意:这个问题是从ECMAScript版本3或5的角度提出的。随着ECMAScript 6版本中新功能的引入,答案可能会过时

JavaScript中
var
关键字的功能到底是什么,它们之间的区别是什么

var someNumber = 2;
var someFunction = function() { doSomething; }
var someObject = { }
var someObject.someProperty = 5;

?


你什么时候会使用其中一个,为什么/它做什么?

如果你在全球范围内,那么没有太大的区别。阅读答案进行解释

如果您在函数中,则
var
将创建一个局部变量,“no var”将查找作用域链,直到找到变量或到达全局作用域(此时将创建变量):

如果您没有做作业,则需要使用
var

var x; // Declare x
<script>
one();

function one()
{
    for (i = 0;i < 10;i++)
    {
        two();
        alert(i);
    }
}

function two()
{
    i = 1;
}
</script>

我想说,在大多数情况下,最好使用
var

局部变量总是比全局范围内的变量快

如果不使用
var
声明变量,则该变量将在全局范围内


有关更多信息,您可以在Google中搜索“范围链JavaScript”。

不带
var
-全局变量

强烈建议始终使用
var
语句,因为本地上下文中的init全局变量是邪恶的。但是,若你们需要这个肮脏的把戏,你们应该在页面的开头写评论:

/* global: varname1, varname2... */

在浏览器中执行Javascript时,所有代码都会被with语句包围,如下所示:

with (window) {
    //Your code
}
更多关于

由于
var
在当前范围内声明变量,因此在窗口内声明
var
与根本不声明变量之间没有区别

当您不直接在窗口内部时,例如在函数内部或在块内部时,就会出现差异

使用
var
可以隐藏具有相同名称的外部变量。通过这种方式,您可以模拟“私有”变量,但这是另一个主题

经验法则是始终使用
var
,否则会有引入细微错误的风险

编辑: 在收到评论后,我想强调以下几点:

  • var
    在当前范围内声明一个变量
  • 全局范围是
    窗口
  • 不使用
    var
    在全局范围(窗口)中隐式声明
    var
  • 使用
    var
    在全局作用域(窗口)中声明变量与省略变量相同
  • 使用
    var
    在不同于窗口的作用域中声明变量与不使用
    var
    声明变量不同
  • 始终显式声明
    var
    ,因为这是一种良好的做法

    • 这里有一个很好的例子,说明了如果不使用
      var
      声明局部变量,您将如何被抓住:

      var x; // Declare x
      
      <script>
      one();
      
      function one()
      {
          for (i = 0;i < 10;i++)
          {
              two();
              alert(i);
          }
      }
      
      function two()
      {
          i = 1;
      }
      </script>
      
      
      一个();
      功能一()
      {
      对于(i=0;i<10;i++)
      {
      二();
      警报(一);
      }
      }
      函数二()
      {
      i=1;
      }
      

      i
      在循环的每次迭代中都会被重置,因为它不是在
      for
      循环中局部声明的,而是全局声明的)最终导致无限循环

      说它是“局部全局之间的差异并不完全准确

      最好将其视为“本地最近的”之间的差异。最近的可能肯定是全球性的,但情况并非总是如此

      /* global scope */
      var local = true;
      var global = true;
      
      function outer() {
          /* local scope */
          var local = true;
          var global = false;
      
          /* nearest scope = outer */
          local = !global;
      
          function inner() {
              /* nearest scope = outer */
              local = false;
              global = false;
      
              /* nearest scope = undefined */
              /* defaults to defining a global */
              public = global;
          }
      }
      

      始终使用
      var
      关键字来声明变量。为什么?良好的编码实践本身就足够了,但省略它意味着它是在全局范围内声明的(这样的变量称为“隐含的”全局变量)。Douglas Crockford,根据:

      不使用
      var创建的任何变量
      关键字是在全局范围内创建的
      并且当
      函数返回(因为它没有
      超出范围),展示
      内存泄漏的机会


      有区别

      var x=1
      在当前范围(也称为执行上下文)中声明变量。如果声明出现在函数中,则声明局部变量;如果它在全局范围内,则声明一个全局变量

      另一方面,
      x=1
      ,仅仅是一种财产分配。它首先尝试根据范围链解析
      x
      。如果它在该范围链中的任何位置找到它,它将执行赋值;如果它没有找到
      x
      ,只有它才会在全局对象上创建
      x
      属性(它是范围链中的顶级对象)

      现在,请注意,它没有声明全局变量,而是创建了一个全局属性

      这两者之间的区别是微妙的,可能会令人困惑,除非您了解变量声明也会创建属性(仅在变量对象上),并且Javascript中的每个属性(好吧,ECMAScript)都有特定的标志来描述它们的属性-ReadOnly、DontEnum和DontDelete

      由于变量声明使用DontDelete标志创建属性,所以
      var x=1
      x=1
      (在全局范围内执行时)之间的区别在于前者-变量声明-创建DontDelete'able属性,而后者不创建。因此,通过此隐式赋值创建的属性可以从全局对象中删除,而前一个属性(通过变量声明创建的属性)不能删除

      但这当然只是理论,在实践中,由于实现中的各种错误(例如来自
      var a = a || [] ; // works 
      
      a = a || [] ; // a is undefined error.
      
      someFunction() {
          var a = some_value; /*a has local scope and it cannot be accessed when this
          function is not active*/
          b = a; /*here it places "var b" at top of script i.e. gives b global scope or
          uses already defined global variable b */
      }
      
      var foo = 5; 
      bar = 2;     
      fooba = 3;
      
      // Execute an anonymous function
      (function() {    
          bar = 100;             //overwrites global scope bar
          var foo = 4;           //a new foo variable is created in this' function's scope
          var fooba = 900;       //same as above
          document.write(foo);   //prints 4
          document.write(bar);   //prints 100
          document.write(fooba); //prints 900
      })();
      
      document.write('<br/>');
      document.write('<br/>');
      document.write(foo);       //prints 5
      document.write(bar);       //prints 100
      document.write(fooba);     //prints 3
      
      my_var;
      
      my_var = "value";
      
      var my_var;
      
      var local = true;
      var global = true;
      
      
      function test(){
        var local = false;
        var global = false;
        console.log(local)
        console.log(global)
      }
      
      test();
      
      console.log(local);
      console.log(global);
      
      var local = true;
      var global = true;
      
      
      function test(){
        local = false;
        global = false;
        console.log(local)
        console.log(global)
      }
      
      test();
      
      console.log(local);
      console.log(global);
      
      a = 1;// Defined outside the function without var
      var b = 1;// Defined outside the function with var
      alert("Starting outside of all functions... \n \n a, b defined but c, d not defined yet: \n a:" + a + "\n b:" + b + "\n \n (If I try to show the value of the undefined c or d, console.log would throw 'Uncaught ReferenceError: c is not defined' error and script would stop running!)");
      
      function testVar1(){
          c = 1;// Defined inside the function without var
          var d = 1;// Defined inside the function with var
          alert("Now inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
      
          a = a + 5;
          b = b + 5;
          c = c + 5;
          d = d + 5;
      
          alert("After added values inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
      };
      
      
      testVar1();
      alert("Run the 1. function again...");
      testVar1();
      
      function testVar2(){
          var d = 1;// Defined inside the function with var
          alert("Now inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
      
          a = a + 5;
          b = b + 5;
          c = c + 5;
          d = d + 5;
      
          alert("After added values inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
      };
      
      testVar2();
      
      alert("Now outside of all functions... \n \n Final Values: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n You will not be able to see d here because then the value is requested, console.log would throw error 'Uncaught ReferenceError: d is not defined' and script would stop. \n ");
      alert("**************\n Conclusion \n ************** \n \n 1. No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.\n 2. If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2() \n 3. If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.");
      alert("Now check console.log for the error when value d is requested next:");
      alert(d);