注意:这个问题是从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以及函数内部或外部的变量时感到困惑。下面是一个深入的示例,将指导您完成以下步骤:
请在jsfiddle查看下面的脚本
a = 1;// Defined outside the function without var
var b = 1;// Defined outside the function with var
alert("Starting outside of all functions... \n \n a, b defined but c, d not defined yet: \n a:" + a + "\n b:" + b + "\n \n (If I try to show the value of the undefined c or d, console.log would throw 'Uncaught ReferenceError: c is not defined' error and script would stop running!)");
function testVar1(){
c = 1;// Defined inside the function without var
var d = 1;// Defined inside the function with var
alert("Now inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
a = a + 5;
b = b + 5;
c = c + 5;
d = d + 5;
alert("After added values inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};
testVar1();
alert("Run the 1. function again...");
testVar1();
function testVar2(){
var d = 1;// Defined inside the function with var
alert("Now inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
a = a + 5;
b = b + 5;
c = c + 5;
d = d + 5;
alert("After added values inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};
testVar2();
alert("Now outside of all functions... \n \n Final Values: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n You will not be able to see d here because then the value is requested, console.log would throw error 'Uncaught ReferenceError: d is not defined' and script would stop. \n ");
alert("**************\n Conclusion \n ************** \n \n 1. No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.\n 2. If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2() \n 3. If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.");
alert("Now check console.log for the error when value d is requested next:");
alert(d);
结论无论是否声明有var(如a、b),如果它们在函数外部获取值,它们都将保留其值,并且通过脚本添加到各个函数内部的任何其他值也将保留。如果在函数(如c)中声明变量时没有var,它将像前面的规则一样,从现在起在所有函数中保留其值。要么在函数testVar1()中获得第一个值,要么仍保留该值,并在函数testVar2()中获取附加值如果变量仅在函数内部用var声明(如testVar1或testVar2中的d),则每当函数结束时,它都将是未定义的。所以它将是函数中的临时变量。
当在浏览器中执行Javascript时,所有代码都被一个with语句包围,如下所示:
with (window) {
//Your code
}
有关-MDN的更多信息
由于var在当前范围内声明了一个变量,所以在窗口内声明var和根本不声明它之间没有区别。
不同的是,当你不直接在窗口内时,例如在函数内或块内。
使用var可以隐藏同名的外部变量。通过这种方式,您可以模拟“私有”变量,但这是另一个主题。
经验法则是始终使用var,否则会有引入细微错误的风险。
编辑:在收到批评之后,我想强调以下几点:
var声明当前范围中的变量全局范围是窗口不使用var在全局范围(窗口)中隐式声明var使用var在全局范围(窗口)中声明变量与省略变量相同。使用var在不同于window的作用域中声明变量与不使用var声明变量不同始终显式声明var,因为这是一种很好的做法
@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)})})