问题描述
也许很简单的问题。
我应该在JavaScript中使用 var
关键字。在我看来使用它或不具有相同的效果(但我当然还在学习语言)
Where should I use var
keyword in JavaScript. It seems to me using it or not have the same effect ( but of course I'm still learning the language )
例如这些对我来说似乎都是一样的:
For instance these both seems the same to me:
(function(){
var a = "mundo"
alert("Hola, " + a )
})()
和
(function(){
a = "mundo"
alert("Hola, " + a )
})()
但当然必须有一个更复杂的例子显示差异。
But of course there must be a more complex example where the difference shows up.
推荐答案
当您使用 var
时,您正在实例化当前范围内的变量。这也将阻止在当前范围内访问更高范围内名为相同的变量。
When you use var
, you are instantiating a variable in the current scope. This will also prevent access of variables named the same in higher scope, within the current scope.
在第一个示例中,'a'正在实例化并在函数内设置范围。在你的第二个例子中,'a'被设置在函数范围之外,因为缺少 var
In your first example, 'a' is being instantiated and set within the function scope. In your second example, 'a' is being set outside the function scope due to lack of var
带 var
:
var a = "A"
(function(){
var a = "B"
alert(a) //B
})()
alert(a); //A
没有 var
:
var a = "A";
(function(){
a = "B"
alert(a) //B
})()
alert(a) //B
这篇关于何时在Javascript中使用var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!