注意:这个问题是从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,则会自动将var_name放在全局范围中,例如:

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

其他回答

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

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

/* 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_name放在全局范围中,例如:

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

<script>
one();

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

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

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

不要使用var!

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

使用常量和let

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

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

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

使用var总是一个好主意,可以防止变量扰乱全局范围,避免变量彼此冲突,导致不必要的覆盖。