在同一范围内两次声明 Javascript 变量 - 这是一个问题吗? [英] Declaring a Javascript variable twice in same scope - Is it an issue?

查看:21
本文介绍了在同一范围内两次声明 Javascript 变量 - 这是一个问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码会导致任何问题吗?:

var a = 1;变量 a = 2;

我的理解是 javascript 变量是在作用域的开始处声明的.例如:

var foo = 'a';foo = 'b';var bar = 'c';

被处理为:

var foo;无功吧;foo = 'a';foo = 'b';酒吧 = 'c';

因此我的初始代码片段会变成:

var a;一 = 1;一 = 2;

或者它会变成:

var a;变量 a;一 = 1;一 = 2;

我知道在同一个范围内两次声明一个 javascript 变量并不是一个好习惯,但我更感兴趣的是这样做的影响.

解决方案

如您所说,通过两倍以上的相同 var,JavaScript 将该声明移动到作用域的顶部,然后您的代码将变成这样:

>

var a;一 = 1;一 = 2;

因此,它不会给我们任何错误.

同样的行为发生在 for 循环中(它们的头部没有局部作用域),所以下面的代码很常见:

for (var i = 0; i 

这就是像 Douglas Crockford 这样的 JavaScript 专家建议程序员手动将这些声明移到作用域顶部的原因:

var i;//在这里声明for (i = 0; i < n; i++) {//在这里初始化...//...}for (i = 0; i 

Would the following code cause any issues?:

var a = 1;
var a = 2;

My understanding is that javascript variables are declared at the start of the scope. For example:

var foo = 'a';
foo = 'b';
var bar = 'c';

Is processed as:

var foo;
var bar;
foo = 'a';
foo = 'b';
bar = 'c';

Therefore would my initial code snippet become:

var a;
a = 1;
a = 2;

Or would it become:

var a;
var a;
a = 1;
a = 2;

I understand that declaring a javascript variable twice in the same scope isn't good practice, but I'm more interested in the impact of doing this.

解决方案

As you said, by twice of more the same var, JavaScript moves that declaration to the top of the scope and then your code would become like this:

var a;
a = 1;
a = 2;

Therefore, it doesn't give us any error.

This same behaviour occurs to for loops (they doesn't have a local scope in their headers), so the code below is really common:

for (var i = 0; i < n; i++) {
    // ...
}
for (var i = 0; i < m; i++) {
    // ...
}

That's why JavaScript gurus like Douglas Crockford suggest programmers to manually move those declarations to the top of the scope:

var i;    // declare here
for (i = 0; i < n; i++) {    // initialize here...
    // ...
}
for (i = 0; i < m; i++) {    // ... and here
    // ...
}

这篇关于在同一范围内两次声明 Javascript 变量 - 这是一个问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆