javascript var 或 not var,有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4385894/
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-10-25 11:14:26  来源:igfitidea点击:

javascript var or not var, what's the difference?

javascript

提问by Shaoz

Possible Duplicate:
Difference between using var and not using var in JavaScript

可能的重复:
在 JavaScript 中使用 var 和不使用 var 的区别

Hi All

大家好

Declaringvar myVar;with varkeyword or declaring myVarwithout it.

var myVar;使用var关键字声明或myVar不使用关键字声明。

This might be a stupid question for some, but I'm in a learning process with javascript.

对于某些人来说,这可能是一个愚蠢的问题,但我正在学习 javascript。

Sometime, when reading other people's code, I see that some variables are declared without the 'var' at the front. Just to emphasise, these variables are not even declared as parameters of a function.

有时,在阅读其他人的代码时,我看到某些变量的声明没有前面的“var”。只是强调一下,这些变量甚至没有被声明为函数的参数。

So what's the difference between declaring a variable with or without the 'var' keyword?

那么声明一个带有或不带有 'var' 关键字的变量有什么区别呢?

Many Thanks

非常感谢

回答by Nick Craver

If you don't use it, it mightbe a global variable, or in IE's case, it'll just blow up.

如果你不使用它,它可能是一个全局变量,或者在 IE 的情况下,它会爆炸。

There are cases you don't need it, for example if it's a parameter to the function you're in, it's already declared. Alwaysuse varin any other cases (other cases being: unless you're manipulating a variable that already exists). No matter what scope it needs to be defined at, explicitlydefine it there.

在某些情况下您不需要它,例如,如果它是您所在函数的参数,则它已被声明。 始终使用var在任何其他情况下(其他情况是:除非你操纵已经存在的变量)。不管它需要在什么范围内定义,在那里明确定义它。

回答by Ollie Edwards

It's all about scoping. Technically you can omit var but consider this:

这都是关于范围界定的。从技术上讲,您可以省略 var 但请考虑:

myVar = "stuff";

function foo() {
    myVar = "junk"; //the original myVar outside the function has been changed
}

function bar() {
    var myVar = "things" //A new scoped myvar has been created internal to the function
}