什么时候在 Javascript 中使用 var

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5398766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:01:22  来源:igfitidea点击:

When to use var in Javascript

javascriptvar

提问by OscarRyz

Maybe pretty easy question.

也许很简单的问题。

Where should I use varkeyword in JavaScript. It seems to me using it or not have the same effect ( but of course I'm still learning the language )

我应该在哪里使用varJavaScript 中的关键字。在我看来,使用它与否具有相同的效果(但当然我仍在学习该语言)

For instance these both seems the same to me:

例如,这两个在我看来都是一样的:

(function(){
  var a = "mundo"
  alert("Hola, " + a )
})()

and

(function(){
  a = "mundo"
  alert("Hola, " + a )
})()

But of course there must be a more complex example where the difference shows up.

但是当然必须有一个更复杂的例子来显示差异。

回答by Bodman

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.

当您使用 时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

在您的第一个示例中,'a' 正在被实例化并在函数范围内设置。在您的第二个示例中,由于缺少var

With var:

var

var a = "A"
(function(){
  var a = "B"
  alert(a) //B
})()

alert(a); //A

Without var:

没有var

var a = "A";
(function(){
  a = "B"
  alert(a) //B
})()

alert(a) //B

回答by Sam Dufel

Using var:

使用变量:

var a = 'world';   
myfunction = function(){
  var a = "mundo"
  alert("Hola, " + a )
}

myfunction();  //alerts 'hola, mundo'
alert(a);  //alerts 'world';

Not using var:

不使用 var:

var a = 'world';   
myfunction = function(){
  a = "mundo"
  alert("Hola, " + a )
}

myfunction();  //alerts 'hola, mundo'
alert(a);  //alerts 'mundo'

回答by It Grunt

I think that you need to refresh yourself on Javascript object scopes.

我认为您需要在 Javascript 对象范围上刷新自己。

Using the "var" keyword will place your variable at the top-most (global) scope. This means that if a function uses the same variable, the "var" variable you declared will overwrite the (non-var) variable in your function... JavaScript Scopes

使用“var”关键字会将您的变量置于最顶层(全局)范围内。这意味着如果函数使用相同的变量,您声明的“var”变量将覆盖函数中的(非 var)变量... JavaScript Scopes

回答by Agonych

if var not used inside function, JS will look for it above, so in case you use save vars in different functions they might conflict. It always worth to use a var if you are defining new variable.

如果 var 没有在函数内部使用,JS 会在上面寻找它,所以如果你在不同的函数中使用 save vars,它们可能会发生冲突。如果您要定义新变量,则始终值得使用 var。