以下两个语句有什么区别?
var temp = 10;
temp = 10;
以下两个语句有什么区别?
var temp = 10;
temp = 10;
如果你在函数内使用"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。
当您在全局范围内定义变量时,您可以在任何地方访问它。如果您使用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;
}
function f(){temp=1}; f(); temp; // 1
。 - user1636522