“var”在 JavaScript 中有什么作用?为什么它有时是作业的一部分?

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

What does "var" do in JavaScript? Why is it sometimes part of an assignment?

javascript

提问by ace

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

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

var foo = 1;

foo = 1;

What is the difference between above two lines ?

以上两行有什么区别?

回答by paxdiablo

Basically, vardeclaresa variable and you can also assign to it at the same time.

基本上,var声明一个变量,您也可以同时分配给它。

Without var, it's assigning to the variable. Assigning will either assign to an existing variable or create a global variable of that name then assign to it.

没有var,它会分配给变量。分配将分配给现有变量或创建该名称的全局变量,然后分配给它。

Outside of functions, that means there's no real difference (in principal) if the variable does not already exist. Both create the global variable fooin that case.

在函数之外,这意味着如果变量不存在,则没有真正的区别(原则上)。foo在这种情况下,两者都会创建全局变量。

Withina function, there's a huge difference. The first creates a variable local to the function regardless of whether or not it exists elsewhere.

一个函数中,有很大的不同。第一个创建函数的局部变量,无论它是否存在于其他地方。

The second will create a global variable if it doesn't exist, or simply change the value if it does exist.

如果它不存在,第二个将创建一个全局变量,或者如果它存在则简单地更改值。

In order to keep code as modular as possible, you should alwaysuse varunless you are specifically wanting to change existing global variables. That means declaring all globals outside of functions with varand declaring all locals with var.

为了使代码尽可能模块化,除非您特别想更改现有的全局变量,否则应始终使用var。这意味着var使用var.

回答by Ry-

foo = 1will put fooin the last scope where foowas defined, or the global scope. var foo = 1will put the variable in the current scope (i.e. the current function).

foo = 1将放入定义foo的最后一个范围foo,或全局范围。var foo = 1将变量放入当前作用域(即当前函数)。

回答by Pavel Podlipensky

In first case foo will be available in the same scope where it is defined, i.e. it will be local variable. In second case foo is a global variable, located in global scope.

在第一种情况下, foo 将在定义它的同一范围内可用,即它将是局部变量。在第二种情况下 foo 是一个全局变量,位于全局范围内。