Javascript 使用“var”来声明变量是可选的吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2485423/
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
Is using 'var' to declare variables optional?
提问by Ray Lu
Is "var" optional?
“var”是可选的吗?
myObj = 1;
same as ?
与...一样 ?
var myObj = 1;
I found they both work from my test, I assume varis optional. Is that right?
我发现它们都在我的测试中工作,我认为var是可选的。那正确吗?
回答by Stefano Borini
They mean different things.
If you use varthe variable is declared within the scope you are in (e.g. of the function). If you don't use var, the variable bubbles up through the layers of scope until it encounters a variable by the given name or the global object (window, if you are doing it in the browser), where it then attaches. It is then very similarto a global variable. However, it can still be deleted with delete(most likely by someone else's code who also failed to use var). If you use varin the global scope, the variable is truly globaland cannot be deleted.
它们的意思不同。如果您使用var变量在您所在的范围内声明(例如函数)。如果您不使用var,则变量会在作用域层中冒泡,直到遇到给定名称的变量或全局对象(窗口,如果您在浏览器中执行此操作),然后将其附加到此处。它非常类似于全局变量。但是,它仍然可以被删除delete(很可能被其他人的代码也没有使用var)。如果var在全局作用域中使用,变量是真正的全局变量,不能删除。
This is, in my opinion, one of the most dangerous issues with javascript, and should be deprecated, or at least raise warnings over warnings. The reason is, it's easy to forget varand have by accident a common variable name bound to the global object. This produces weird and difficult to debug behavior.
在我看来,这是 javascript 中最危险的问题之一,应该弃用,或者至少对警告提出警告。原因是,很容易忘记var并意外地将公共变量名称绑定到全局对象。这会产生奇怪且难以调试的行为。
回答by deceze
This is one of the tricky parts of Javascript, but also one of its core features. A variable declared with var"begins its life" right where you declare it. If you leave out the var, it's like you're talking about a variable that you have used before.
这是 Javascript 的棘手部分之一,但也是其核心功能之一。一个用var“开始它的生命”声明的变量就在你声明它的地方。如果您省略var,就好像您在谈论您以前使用过的变量。
var foo = 'first time use';
foo = 'second time use';
With regards to scope, it is nottrue that variables automatically become global. Rather, Javascript will traverse up the scope chain to see if you have used the variable before. If it finds an instance of a variable of the same name used before, it'll use that and whatever scope it was declared in. If it doesn't encounter the variable anywhere it'll eventually hit the global object (windowin a browser) and will attach the variable to it.
关于作用域,变量自动变为全局是不正确的。相反,Javascript 将遍历作用域链以查看您之前是否使用过该变量。如果它找到以前使用的同名变量的实例,它将使用该实例以及它声明的任何范围。如果它在任何地方都没有遇到该变量,它最终将命中全局对象(window在浏览器中)并将变量附加到它。
var foo = "I'm global";
var bar = "So am I";
function () {
var foo = "I'm local, the previous 'foo' didn't notice a thing";
var baz = "I'm local, too";
function () {
var foo = "I'm even more local, all three 'foos' have different values";
baz = "I just changed 'baz' one scope higher, but it's still not global";
bar = "I just changed the global 'bar' variable";
xyz = "I just created a new global variable";
}
}
This behavior is really powerful when used with nested functions and callbacks. Learning about what functionsare and how scope works is the most important thing in Javascript.
当与嵌套函数和回调一起使用时,这种行为非常强大。functions了解作用域是什么以及如何工作是 Javascript 中最重要的事情。
回答by Eineki
Nope, they are not equivalent.
不,它们不是等价的。
With myObj = 1;you are using a global variable.
随着myObj = 1;你使用全局变量。
The latter declaration create a variable local to the scope you are using.
后一个声明创建一个局部于您正在使用的范围的变量。
Try the following code to understand the differences:
尝试以下代码以了解差异:
external = 5;
function firsttry() {
var external = 6;
alert("first Try: " + external);
}
function secondtry() {
external = 7;
alert("second Try: " + external);
}
alert(external); // Prints 5
firsttry(); // Prints 6
alert(external); // Prints 5
secondtry(); // Prints 7
alert(external); // Prints 7
The second function alters the value of the global variable "external", but the first function doesn't.
第二个函数改变全局变量“external”的值,但第一个函数不会。
回答by bcherry
There's a bit more to it than just local vs global. Global variables created with varare different than those created without. Consider this:
除了本地与全局之外,还有更多内容。创建的全局变量与var没有创建的全局变量不同。考虑一下:
var foo = 1; // declared properly
bar = 2; // implied global
window.baz = 3; // global via window object
Based on the answers so far, these global variables, foo, bar, and bazare all equivalent. This is notthe case. Global variables made with varare (correctly) assigned the internal [[DontDelete]]property, such that they cannot be deleted.
根据目前的答案,这些全局变量foo、bar、 和baz都是等价的。这是不是这种情况。用 制作的全局变量var(正确)分配了内部[[DontDelete]]属性,因此它们不能被删除。
delete foo; // false
delete bar; // true
delete baz; // true
foo; // 1
bar; // ReferenceError
baz; // ReferenceError
This is why you should alwaysuse var, even for global variables.
这就是为什么您应该始终使用var,即使对于全局变量也是如此。
回答by Steve Kallestad
There's so much confusion around this subject, and none of the existing answers cover everything clearly and directly. Here are some examples with comments inline.
围绕这个主题有很多混乱,现有的答案都没有清楚直接地涵盖所有内容。以下是一些带有内联注释的示例。
//this is a declaration
var foo;
//this is an assignment
bar = 3;
//this is a declaration and an assignment
var dual = 5;
A declaration sets a DontDelete flag. An assignment does not.
声明设置 DontDelete 标志。作业没有。
A declaration ties that variable to the current scope.
声明将该变量与当前作用域联系起来。
A variable assigned but not declared will look for a scope to attach itself to. That means it will traverse up the food-chain of scope until a variable with the same name is found. If none is found, it will be attached to the top-level scope (which is commonly referred to as global).
已分配但未声明的变量将寻找将其自身附加到的作用域。这意味着它将沿着作用域的食物链向上遍历,直到找到具有相同名称的变量。如果没有找到,它将附加到顶级范围(通常称为全局范围)。
function example(){
//is a member of the scope defined by the function example
var foo;
//this function is also part of the scope of the function example
var bar = function(){
foo = 12; // traverses scope and assigns example.foo to 12
}
}
function something_different(){
foo = 15; // traverses scope and assigns global.foo to 15
}
For a very clear description of what is happening, this analysis of the delete functioncovers variable instantiation and assignment extensively.
为了非常清楚地描述正在发生的事情,对删除函数的分析广泛地涵盖了变量实例化和赋值。
回答by kzh
varis optional. varputs a variable in local scope. If a variable is defined without var, it is in global scope and not deletable.
var是可选的。var将变量放入局部作用域。如果变量没有定义var,则它在全局范围内且不可删除。
edit
编辑
I thought that the non-deletable part was true at some point in time with a certain environment. I must have dreamed it.
我认为不可删除的部分在特定环境的某个时间点是正确的。我一定是在做梦。
回答by Milk Man
Check out this Fiddle: http://jsfiddle.net/GWr6Z/2/
看看这个小提琴:http: //jsfiddle.net/GWr6Z/2/
function doMe(){
a = "123"; // will be global
var b = "321"; // local to doMe
alert("a:"+a+" -- b:"+b);
b = "something else"; // still local (not global)
alert("a:"+a+" -- b:"+b);
};
doMe()
alert("a:"+a+" -- b:"+b); // `b` will not be defined, check console.log
回答by SLaks
Undeclared variable (without var) are treated as properties of the global object. (Usually the windowobject, unless you're in a withblock)
未声明的变量(没有var)被视为全局对象的属性。(通常是window对象,除非你在一个with块中)
Variables declared with varare normal local variables, and are not visible outside the function they're declared in. (Note that Javascript does not have block scope)
用 with 声明的变量var是普通的局部变量,在它们声明的函数之外是不可见的。(注意 Javascript 没有块作用域)
回答by Cyril Gupta
The var keyword in Javascript is there for a purpose.
Javascript 中的 var 关键字是有目的的。
If you declare a variable without the var keyword, like this:
如果你声明一个没有 var 关键字的变量,像这样:
myVar = 100;
It becomes a global variable that can be accessed from any part of your script. If you did not do it intentionally or are not aware of it, it can cause you pain if you re-use the variable name at another place in your javascript.
它成为一个全局变量,可以从脚本的任何部分访问。如果您不是故意这样做或没有意识到这一点,那么如果您在 javascript 中的其他地方重新使用变量名称,可能会导致您痛苦。
If you declare the variable with the var keyword, like this:
如果使用 var 关键字声明变量,如下所示:
var myVar = 100;
It is local to the scope ({] - braces, function, file, depending on where you placed it).
它是作用域本地的({] - 大括号、函数、文件,取决于您放置它的位置)。
This a safer way to treat variables. So unless you are doing it on purpose try to declare variable with the var keyword and not without.
这是一种更安全的处理变量的方法。因此,除非您是故意这样做的,否则请尝试使用 var 关键字声明变量而不是没有。
回答by Leniel Maccaferri
Consider this question asked at StackOverflow today:
考虑今天在 StackOverflow 上提出的这个问题:
A good test and a practical exampleis what happens in the above scenario...
The developer used the name of the JavaScript function in one of his variables.
一个很好的测试和一个实际的例子是在上面的场景中发生的事情......
开发人员在他的一个变量中使用了 JavaScript 函数的名称。
What's the problem with the code?
The code only works the first time the user clicks the button.
代码有什么问题?
该代码仅在用户第一次单击按钮时起作用。
What's the solution?
Add the varkeyword before the variable name.
解决办法是什么?在变量名前
添加var关键字。

