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

?

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


当前回答

@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)})})

其他回答

说这是“本地和全球”的区别并不完全准确。

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

/* 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!

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

使用常量和let

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

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

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

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

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声明局部变量:

<script>
one();

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

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

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

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

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

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

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