重新声明 JavaScript 变量有什么目的吗?

发布于 2024-08-13 18:39:52 字数 355 浏览 7 评论 0原文

我是 JavaScript 新手。

<html>
<body>
<script type="text/javascript">
var x=5;
document.write(x);
document.write("<br />");
var x;
document.write(x);
</script>
</body>
</html>

结果是:

5
5

当第二次声明x时,它应该是未定义的,但它保留了以前的值。请解释此重新声明是否有任何特殊目的。

I am new to JavaScript.

<html>
<body>
<script type="text/javascript">
var x=5;
document.write(x);
document.write("<br />");
var x;
document.write(x);
</script>
</body>
</html>

Result is:

5
5

When x is declared the second time it should be undefined, but it keeps the previous value. Please explain whether this redeclaration has any special purpose.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

够运 2024-08-20 18:39:52

您实际上并没有重新声明变量。

JavaScript 中的变量语句会被提升,这意味着它们在解析时进行评估,然后在运行时进行赋值。

在解析阶段结束、执行之前的代码如下所示:

var x;
x = 5;

document.write(x);
document.write("<br />");
document.write(x);

You aren't really re-declaring the variable.

The variable statement in JavaScript, is subject to hoisting, that means that they are evaluated at parse-time and later in runtime the assignments are made.

Your code at the end of the parse phase, before the execution looks something like this:

var x;
x = 5;

document.write(x);
document.write("<br />");
document.write(x);
万劫不复 2024-08-20 18:39:52

var 单独不执行赋值。它仅标志着当您在 var 出现的整个范围内使用变量名称时,您正在谈论的是局部变量而不是全局变量(有争议的默认值)。解析函数时会发现 var 并在整个作用域中保存,因此您将其放在哪里是无关紧要的:

var a= 0;

function foo() {
    a= 1;
    return a;
    var a;
}

var b= foo();
alert('global a='+a+', local a='+b);

结果为 global a= 0, local a= 1:甚至尽管在执行 foo() 的过程中从未到达 var 语句,但它仍然可以有效地使 a 成为局部变量。

因此,在同一范围内第二次声明 var x 是完全多余的。但是,有时您可能仍然会这样做,通常是当您在同一函数中重复使用局部变量名称以进行第二次独立使用时。最常见的是:

for (var i= 0; i<onething.length; i++) {
    ...do some trivial loop...
}

for (var i= 0; i<anotherthing.length; i++) {
    ...do another trivial loop...
}

虽然您当然可以省略第二个 var,并且像 jslint 这样的工具会要求您这样做,但这实际上可能不是一个好主意。

想象一下,您稍后更改或删除第一个循环,以便它不再将 i 声明为 var。现在剩下的第二个循环突然将含义从局部变量更改为全局变量。如果您在更新第一个循环时没有注意到第二个循环对它有隐藏的依赖关系(考虑到眼睛如何忽略模式 for(...=0 ; .. .<...; ...++) 变成“哦,这只是一个标准迭代器”),你遇到了一个微妙且烦人的调试问题。

var alone does not perform an assignment. It only flags that when you use the variable name throughout the scope in which the var occurs, you are talking about a local variable and not global (the controversial default). The var is spotted when the function is parsed and holds throughout that scope, so where you put it is irrelevant:

var a= 0;

function foo() {
    a= 1;
    return a;
    var a;
}

var b= foo();
alert('global a='+a+', local a='+b);

Results in global a= 0, local a= 1: even though the var statement is never reached in the course of execution of foo(), it is still effective in making a a local variable.

So declaring var x a second time in the same scope is completely redundant. However you might sometimes still do it, typically when you re-use a local variable name for a second independent use within the same function. Most commonly:

for (var i= 0; i<onething.length; i++) {
    ...do some trivial loop...
}

for (var i= 0; i<anotherthing.length; i++) {
    ...do another trivial loop...
}

Whilst you could certainly omit the second var, and tools like jslint would demand you do so, it might not actually be a good idea.

Imagine you later change or remove the first loop so that it no longer declares i to be var. Now the remaining second loop suddenly changes meaning from a local to a global variable. If you fail to notice when updating the first loop that the second loop has a hidden dependency on it (and you might very well fail to notice that given how the eyes elide the pattern for(...=0 ; ...<...; ...++) into “oh, that's just a standard iterator”), you've got a subtle and annoying-to-debug problem.

说不完的你爱 2024-08-20 18:39:52

所以当第二次声明的 x 应该是未定义的时

规范的哪一部分这么说呢?

“未定义的行为”并不意味着“变量将是未定义”。

so when the second time when its declared x should be undefined

What part of the specification says this?

"Undefined behaviour" does not mean "the variable will be undefined".

过去的过去 2024-08-20 18:39:52

就我对 javascript 的理解而言,var 关键字的使用在全局范围内是完全可选的。对于函数来说这是一个不同的故事。

在函数内部时,使用 var 关键字来指示该变量是函数的局部变量(而不是默认情况下的全局变量)。

我个人在全局范围内使用 var 来显示变量是第一次被声明和/或使用。

您可以参考http://www.w3schools.com/js/js_variables.asp了解更多信息。

As far as my understanding of javascript goes, the use of the var keyword is completely optional in the global scope. It's a different story for functions.

When inside a function, use the var keyword to indicate that the variable is local to the function (as opposed to being global by default).

I personally use var in the global scope to show that a variable is being declared and/or utilized for the first time.

You can reference http://www.w3schools.com/js/js_variables.asp for more info.

背叛残局 2024-08-20 18:39:52

第二个 var x 是完全多余的。

That second var x is totally superfluous.

青衫儰鉨ミ守葔 2024-08-20 18:39:52

同一作用域内,完全没有必要“重新声明”一个变量。

Within the same scope, it is totally unnecessary to "redeclare" a variable.

春风十里 2024-08-20 18:39:52

此外,程序员可能希望使用 var 来本地化变量:

<script>
var x= 'this is global x';
function my_x() {
 var x= 'localized x';
 alert(x);
}
my_x();
alert(x);
</script>

Also, a programmer might want to use var to localize a variable:

<script>
var x= 'this is global x';
function my_x() {
 var x= 'localized x';
 alert(x);
}
my_x();
alert(x);
</script>
眼眸印温柔 2024-08-20 18:39:52

您不应该永远在同一范围内重新声明变量,如果您确实想更改它,则分配给它。在这种动态语言中创建不同的对象不需要重新声明,如果您希望 x 是一个字符串,只需分配:

x = "hello";

不需要先将其设置回未定义或重新声明。

请注意,在大多数情况下,更改变量类型并不是很好的做法,只需说明如果您需要的话,这是可能的。

You should never redeclare a variable within the same scope, if you really want to change this then assign to it. Redeclaration is not required to create a different object in this dynamic language, if you want x to be a string just assign:

x = "hello";

It is not required that you set it back to undefined or redeclare first.

Please note that changing the variable type is not very good practice in most situations, simply stating that it is a possibility if that's what you require.

裂开嘴轻声笑有多痛 2024-08-20 18:39:52

我最近写了这样的代码:(

var obj1 = get_an_object();
var v = obj1.get_velocity();
v += changes_in_velocity();
obj1.set_velocity(v);

var obj2 = get_an_object();
var v = obj2.get_velocity();
v += changes_in_velocity();
obj2.set_velocity(v);

实际代码更复杂,重复性更少)

就浏览器而言,第二个 var v 语句是多余且毫无意义的。对我来说,它有两个目的。它说忘记我所知道的关于旧 v 的一切,因为这是一种新用法。这意味着我可以重新排序代码,或者注释掉前半部分,而不会破坏任何东西。

I recently wrote code like:

var obj1 = get_an_object();
var v = obj1.get_velocity();
v += changes_in_velocity();
obj1.set_velocity(v);

var obj2 = get_an_object();
var v = obj2.get_velocity();
v += changes_in_velocity();
obj2.set_velocity(v);

(The actual code was more complicated and less repetitive)

So far as the browser is concerned, the second var v statement was redundant and pointless. To me, it served two purposes. It said to forget everything I knew about the old v, because this was a new usage. And it meant I could re-order the code, or comment out the first half, without breaking things.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文