注意:这个问题是从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;

?

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


当前回答

除了范围问题,一些人也提到了吊装,但并没有人举例说明。这里有一个全局范围:

console.log(noErrorCase);var noErrorCase=“您将到达该点”;

console.log(runTimeError);runTimeError=“您不会到达该点”;

其他回答

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

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

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

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

始终使用var关键字声明变量。为什么?良好的编码实践本身应该是足够的理由,但省略它意味着它是在全局范围内声明的(像这样的变量称为“隐含的”全局变量)。Douglas Crockford建议不要使用隐含的全局变量,并且根据Apple 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 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

不要使用var!

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

使用常量和let

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

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

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