JavaScript变量中带有var和不带var的区别是什么?

11

以下两个语句有什么区别?

var temp = 10;
temp = 10;

4
这是一个作用域前缀。使用var声明变量会使其成为局部变量,不使用则会成为全局变量,在严格模式下未声明的变量会导致错误。 - dandavis
@dandavis -- 如果我在函数内部使用 "temp = 10;",那它是全局的还是局部的? - Dixit Singla
1
@DixitSingla 显然,全局变量:function f(){temp=1}; f(); temp; // 1 - user1636522
2个回答

13

如果你在函数内使用"var"声明一个变量,那么它将局限于该函数内部。否则,js引擎会在本地作用域(即函数)中查找该变量,如果找不到,则会自动在全局空间中声明该变量。

参考链接:https://www.inkling.com/read/javascript-definitive-guide-david-flanagan-6th/chapter-3/variable-scope

当你声明一个全局的JavaScript变量时,实际上是定义了全局对象的一个属性(全局对象)。如果使用var来声明该变量,则创建的属性是不可配置的(请参见属性特性),这意味着它无法通过delete运算符进行删除。

然后,如果你在函数或全局空间中执行以下操作:

temp=10;

你可以在任何地方使用它,例如:

console.log(window.temp);

这仅仅是一堆嵌套的函数(为了更好地理解,请阅读代码注释,从内部函数开始):

//lots of stuff here but not a "var temp=9"

//I couldn't find "x" I will make it global as a property of the globalObject
 function myFunction(){ //is x here ? no ? then look outside
    (function(){ //is x here ? no ? then look outside
        (function() {  //is x here ? no ? then look outside
                x=5; //declaring x without var, I will look for it
        }());
    }());
}

myFunction();
console.log(window.x); //As x was declared a property from the global object I can do this.

如果你在函数内使用 var 声明变量,你无法使用 window.temp(变量没有提升),如果你将其放在函数内部,则该变量将是您函数的“本地”变量(不会被提升),例如:

foo = 1;
function test() {
    var foo = 'bar';
}
test();
alert(foo);

// Result: 1

此处有样例及其他内容

同时请注意,在函数外使用“var”将创建一个全局变量(即window对象中的属性) 顺便说一句,始终使用var。


那么为什么是http://jsfiddle.net/arunpjohny/U7Kg5/1/? - Arun P Johny
这段代码将输出 在9 (console.log('in', temp)) (console.log('out', temp)) 将会报错,显示temp未定义 它永远不会执行 " function x " - Dixit Singla
temp 在 anom 函数中被声明,它在函数内部工作,因为你正在自执行该函数,外部无法工作,因为它没有被声明。函数 x() 从未被调用,因此 temp 没有被修改。如果你调用 x(),则第一个 console.log 中的 temp 将为 10,因为它在先前的范围(来自 anom 函数)中“找到”了 temp。 - Allende

0

当您在全局范围内定义变量时,您可以在任何地方访问它。如果您使用var重新定义它,则该变量仅在当前范围内具有该值。

在全局范围内定义一个变量:

var a = 1;

现在你可以通过函数作用域像这样访问它:
function print() {
  console.log(window.a); // 1
  window.a = 5;
  anotherFunction(); // 5 
  var a = 3;
  console.log(a); // 3
}
function anotherFunction() {
  console.log(a); // 5;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接