重新声明一个 javascript 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6888506/
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
Redeclaring a javascript variable
提问by xralf
回答by ThatGuy
It's nothing more than a reminder that if you do this:
这无非是提醒您,如果您这样做:
var x=5;
var x;
alert(x);
Result will be 5.
结果将是 5。
If you re-declare variable in some other languages for example - result will be undefined, or NaN, but not in javascript.
例如,如果您在某些其他语言中重新声明变量 - 结果将是未定义的,或 NaN,但不是在 javascript 中。
回答by Steve Oliver
An example of redeclaring a variable can be found in Google Analytics. When the JavaScript tracking code is initiated by the Google Analytics script, it declares or redeclares _gaq
in this way:
可以在Google Analytics 中找到重新声明变量的示例。当 Google Analytics 脚本启动 JavaScript 跟踪代码时,它_gaq
以这种方式声明或重新声明:
var _gaq = _gaq || [];
In other words, if _gaq
is already defined, _gaq
is "redeclared" as itself. If it is not defined, it will be declared for the first time as an empty array.
换句话说,如果_gaq
已经定义,_gaq
则“重新声明”为它自己。如果未定义,则首次声明为空数组。
This allows the Google Analytics tracking code to support other scripts which may need to use the variable before Google Analytics code has initiated. As @xralf pointed out, JavaScript allows for this.
这允许 Google Analytics 跟踪代码支持其他脚本,这些脚本可能需要在 Google Analytics 代码启动之前使用该变量。正如@xralf 指出的那样,JavaScript 允许这样做。
Redeclaring a variable is useful in situations where it cannot be known if the variable has already been defined.
在无法知道变量是否已定义的情况下,重新声明变量很有用。
By redeclaring a variable conditionally, as Google Analytics tracking code does, it allows for a variable to safely originate from more than one place.
通过有条件地重新声明一个变量,就像 Google Analytics 跟踪代码所做的那样,它允许一个变量安全地来自多个地方。
In this example it could be safe for other code using the _gaq
variable to likewise check for a predefined _gaq
variable. If it exists, it knows it can use it. If it doesn't exist, it knows that it should define it before trying to use it.
在这个例子中,使用该_gaq
变量的其他代码同样检查预定义的_gaq
变量可能是安全的。如果它存在,它知道它可以使用它。如果它不存在,它知道应该在尝试使用它之前定义它。
回答by Quentin
Why should I redeclare a variable?
为什么要重新声明变量?
You shouldn't. It makes for confusing code.
你不应该。它使代码变得混乱。
Is it practical in some situations?
在某些情况下是否实用?
No.
不。
回答by George Filippakos
In javascript there is no block scope so it is advisable to redeclare a variable for clarification purposes; this makes for better code.
在 javascript 中没有块作用域,因此建议重新声明一个变量以进行澄清;这有助于编写更好的代码。
For example:
例如:
for (var x=0; x< 100; x++) { }
alert(x); //In most languages, x would be out of scope here.
//In javascript, x is still in scope.
//redeclaring a variable helps with clarification:
var x = "hello";
alert(x);
回答by roro
It doesn't lose it's value because of Hoisting
不会因为吊装而失去价值
var x = 5;
var x;
// this is same as
var x; // undefined;
x = 5;
So when you say "If you redeclare a JavaScript variable, it will not lose its value."
所以当你说“如果你重新声明一个 JavaScript 变量,它不会失去它的价值。”
As per hoisting, the declaration(s), all of them , move to the top. And thenthe variable is assigned.
根据提升,所有声明都移到顶部。然后变量被赋值。
var x = 25;
var x; // redeclare first time
var x; // redeclare second time
// is same as
var x; // undefined
var x; // Not sure if this happens, but doesn't make a difference, it's still undefined
x = 25;
As for practicality, it happens sometimes. Look at @steveoliver 's answer.
至于实用性,它有时会发生。看看@steveoliver 的回答。
回答by CertainPerformance
Keep in mind that only variables declared with var
can be re-declared. If you try to re-declare a variable declared with let
or const
(which is the ES2015 Javascript syntax that should be used in most cases nowadays), even worse than losing the value, an errorwill be thrown:
请记住,只有用 声明的变量var
才能重新声明。如果你试图重新声明一个用let
or声明的变量const
(这是现在大多数情况下应该使用的 ES2015 Javascript 语法),甚至比丢失值更糟糕,将抛出错误:
let foo = 'foo';
let foo;
So, in codebases which use modern Javascript syntax, re-declaring a variable simply isn't possible - the interpreter needs to be able to identify a single pointin the code after which a let
or const
variable gets properly initialized. Before that point, the variable name will exist in the temporal dead zone.
因此,在使用现代 Javascript 语法的代码库中,根本不可能重新声明变量 - 解释器需要能够识别代码中的单个点,之后 a let
orconst
变量被正确初始化。在此之前,变量名称将存在于时间死区中。
回答by Felix
In general, it can be considered bad style to have var
assignments after other statements due to the problem of hoisting (see here). Using the "Single var pattern" (see here), redeclarations could only happen like in Steve Oliver's Google Analtyics example. I'd refactor the example above to:
一般来说,var
由于提升的问题,在其他语句之后进行赋值可以被认为是不好的风格(见这里)。使用“Single var 模式”(参见此处),重新声明只能发生在 Steve Oliver 的 Google Analtyics 示例中。我将上面的示例重构为:
var x, max = 100; // no further var declarations afterwards!
for (x = 0; x < max; x++) { }
alert(x);
// redeclaration 'var x = "hello"' doesn't make any sense here
// and would be complained about by JSLint/-Hint
x = 'hello';
alert(x);
A redeclaration can make sense however when using default values for optional parameters (which is what the Google Analytics example is about, I assume):
然而,当对可选参数使用默认值时,重新声明是有意义的(我假设这是 Google Analytics 示例的内容):
function abc(param1) {
var param1 = param1 || 'default value';
}