注意:这个问题是从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”变量只能在设置值时定义。例如:

my_var;

不能在全局范围或任何其他范围内工作。它应该具有如下值:

my_var = "value";

另一方面,你可以定义一个可用的类;

var my_var;

它的值未定义(有趣的是,它的值不为null,也不等于null)。

其他回答

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

如果运行此代码:

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。

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

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

/* 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 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关键字。这里有一个链接,用和wihtout var关键字解释全局作用域和本地作用域之间的区别。

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

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

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

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

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

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

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