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

其他回答

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

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

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

@Chris S给出了一个很好的例子,展示了var和no var之间的实际差异(和危险)。这是另一个例子,我发现这一点特别危险,因为这种差异只在异步环境中可见,因此在测试过程中很容易溜走。

正如您预期的那样,以下代码段输出[“text”]:

函数var_fun(){let数组=[]array.push('text')返回数组}console.log(var_fun())

下面的代码段也是如此(请注意缺少的let before数组):

函数var_fun(){数组=[]array.push('text')返回数组}console.log(var_fun())

异步执行数据操作仍然会使用单个执行器产生相同的结果:

函数var_fun(){array=[];return new Promise(resolve=>resolve()).then(()=>{array.push('text')返回数组})}var_fun().then(result=>{console.log(result)})

但对多个对象的行为不同:

函数var_fun(){array=[];return new Promise(resolve=>resolve()).then(()=>{array.push('text')返回数组})}[1,2,3].对于每个(i=>{var_fun().then(result=>{console.log(result)})})

但是,使用let:

函数var_fun(){let数组=[];return new Promise(resolve=>resolve()).then(()=>{array.push('text')返回数组})}[1,2,3].对于每个(i=>{var_fun().then(result=>{console.log(result)})})

这是我为您编写的用于理解这一概念的示例代码:

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

如果你在全球范围内,那就没有太大区别了。阅读Kangax的答案以获得解释

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

// These are both globals
var foo = 1;
bar = 2;

function()
{
    var foo = 1; // Local
    bar = 2;     // Global

    // Execute an anonymous function
    (function()
    {
        var wibble = 1; // Local
        foo = 2; // Inherits from scope above (creating a closure)
        moo = 3; // Global
    }())
}

如果您没有执行赋值,则需要使用var:

var x; // Declare x

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

<script>
one();

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

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

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