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

JavaScript中var关键字的功能是什么

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

and

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

?

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


当前回答

下面是一个很好的例子,说明如何避免使用var声明局部变量:

<script>
one();

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

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

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

其他回答

我看到人们在声明带有或不带有var以及函数内部或外部的变量时感到困惑。下面是一个深入的示例,将指导您完成以下步骤:

请在jsfiddle查看下面的脚本

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);

结论无论是否声明有var(如a、b),如果它们在函数外部获取值,它们都将保留其值,并且通过脚本添加到各个函数内部的任何其他值也将保留。如果在函数(如c)中声明变量时没有var,它将像前面的规则一样,从现在起在所有函数中保留其值。要么在函数testVar1()中获得第一个值,要么仍保留该值,并在函数testVar2()中获取附加值如果变量仅在函数内部用var声明(如testVar1或testVar2中的d),则每当函数结束时,它都将是未定义的。所以它将是函数中的临时变量。

不要使用var!

var是ES6之前声明变量的方法。我们现在在未来,你应该这样编码。

使用常量和let

约95%的病例应使用常量。它使变量引用不能更改,因此数组、对象和DOM节点财产可以更改,并且应该是常量。

let应该用于任何期望重新分配的变量。这包括在for循环中。如果在初始化之后写入varName=,请使用let。

这两种语言都具有块级作用域,正如大多数其他语言所期望的那样。

除非您希望将变量附加到浏览器中的窗口对象,否则应该使用var关键字。这里有一个链接,用和wihtout var关键字解释全局作用域和本地作用域之间的区别。

当在不使用var关键字的情况下定义变量时,它看起来像是一个简单的“赋值”操作。

当将值分配给javascript中的变量时,解释器首先尝试在与赋值相同的上下文/范围中查找“变量声明”。当解释器执行dummyVariable=20时,它会在函数开头查找dummyVariable的声明。(因为javascript解释器将所有变量声明移动到上下文的开头,这称为提升)

您可能还想看看javascript中的提升

当有些人试图学习这一点时,我是这样看的。对于初学者来说,上面的例子可能有点过于复杂。

如果运行此代码:

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);

输出将为:false,false,true,true

因为它认为函数中的变量与函数外的变量是分开的,因此称为局部变量,这是因为我们在赋值中使用了var。如果你去掉函数中的var,那么它现在看起来像这样:

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);

输出为false、false、false和false

这是因为它没有在局部范围或函数中创建新变量,而是简单地使用全局变量并将其重新赋值为false。

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

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

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

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