简体   繁体   English

多次声明变量

[英]Declaring variables multiple times

for(var i = 0; i < 100; i++){
  var foo = 5;

}

It works ...but is this bad? 它有效...但是这很糟糕吗?

I know I can declare var foo outside, but why do that when I'm only going to use it in the loop? 我知道我可以在外面声明var foo ,但为什么在我只在循环中使用它时呢?

Over time my personal style has grown into a preference for declaring variables where they "actually are" in the "mind" of the particular language I am working in. For JavaScript this means putting variable and function declarations in the positions where the language would hoist them anyway. 随着时间的推移,我的个人风格已经变得偏向于在我正在使用的特定语言的“思维”中声明变量“实际上”。对于JavaScript,这意味着将变量和函数声明放在语言将提升的位置无论如何他们。

This is for clarity, precise communication, understanding, maintainability, to keep my own mental processes parallel with the processes of the language, just to mention a few good reasons. 这是为了清晰,准确的沟通,理解,可维护性,以保持我自己的心理过程与语言的过程平行,只是提到一些很好的理由。

So in this particular case, I would not put a var foo = 5; 所以在这种特殊情况下,我不会把var foo = 5; declaration into the body of a for loop, for the simple reason that it is not doing what it looks like it is doing, ie, it is not in fact redeclaring/re-scoping the variable with every iteration. 声明进入for循环的主体,原因很简单,它没有做它看起来正在做的事情,也就是说,它实际上并没有在每次迭代时重新声明/重新定义变量。 (Placing the var declaration in the initialization portion of the for loop's header (initialization; condition; afterthought) would be more reasonable, and certainly the correct place to put it in languages that do have block-level variables, such as when JavaScript finishes adopting the let -style declaration for block-level scope.) (将var声明放在for循环标题的初始化部分(初始化;条件;事后补充)会更合理,当然也是将它放在具有块级变量的语言中的正确位置,例如当JavaScript完成采用时块级范围的let -style声明。)

Notes: 笔记:

  • This practice may not seem "normal." 这种做法似乎并不“正常”。 My mind prefers to keep variables "close" to their use, and my current practice does not come naturally to the way my mind works. 我的思维倾向于保持变量“接近”它们的使用,而我现在的做法并不是我思想工作的方式。 But as a programmer through the years, experiences with confusion, bad communication, misunderstanding, unmaintainable code impossible to unravel, etc., have more than justified the extra discipline that it takes me to follow this style of declaring variables in the locations corresponding to their actual scope, regardless of the language. 但作为一名多年来的程序员,经验混乱,沟通不畅,误解,不可维护的代码无法解开等等,除了证明在我们对应的位置上遵循这种声明变量的方式时,我还有更多的理由。实际范围,无论语言如何。

  • One extra benefit of this practice for me has been that it encourages me to keep my functions modular and reasonable in size. 这种做法的另一个好处是,它鼓励我保持我的功能模块化和合理的尺寸。

  • Along the same lines, following this practice automatically helps keep my code organized in a sensible way. 沿着同样的路线,遵循这种做法自动有助于保持我的代码以合理的方式组织。 For instance, if putting my functions first causes there to be excessive functions before the code I am actually working on, and I therefore get irritated about having to go down two pages to edit my program, following this style automatically gives me incentive to organize my code into an appropriate structure of distinct files. 例如,如果首先放置我的函数会导致在我实际处理的代码之前出现过多的函数,因此我不得不下两页来编辑我的程序,因此遵循此样式会激励我组织我的将代码编码到不同文件的适当结构中。

PS One could bring up a point that some functions are so long that this practice makes variable declarations end up pages away from where they are used. PS One可以提出一个观点,即某些函数是如此之长,以至于这种做法使得变量声明最终会使页面远离它们的使用位置。 Yes, I have seen code where that is true, and perhaps even code where that cannot be helped. 是的,我已经看到代码在哪里是真的,甚至可能代码无法帮助的代码。 Yet I can't help observing the parallel that is equally true for authors of prose as it is for computer programmers. 然而,我无法观察到对于散文作者和计算机程序员同样如此的平行。 As skill level grows, the lengths of authors' sentences (and sizes of programmers' functions) tend to grow, and then as the skill level continues to grow yet higher, the lengths of sentences (and sizes of programmer's functions) tend to shorten once more. 随着技能水平的提高,作者句子的长度(以及程序员函数的大小)趋于增长,然后随着技能水平的不断提高,句子的长度(以及程序员函数的大小)往往会缩短一次更多。

It is bad because it gives the false impression that i and foo are local variables. 这很糟糕,因为它给人以错误的印象,即ifoo是局部变量。

for(var i = 0; i < 100; i++){
    var foo = 5;
}
foo; // 5

This might not be a problem with simple code, but if you use closures it becomes apparent that there is only one foo : 这可能不是简单代码的问题,但如果你使用闭包,很明显只有一个foo

var counters = [];
for (var i = 0; i < 100; i++) {
    var foo = 5;
    counters.push(function() { foo++; return foo; });
}
counters[0](); // 6
counters[0](); // 7
counters[1](); // 8 (!)

To create foo in a different scope a function needs to be introduced: 要在不同的范围内创建foo ,需要引入一个函数:

var counters = [];
for (var i = 0; i < 100; i++) {
    (function() {
        var foo = 5;
        counters.push(function() { foo++; return foo; });
    })();
}
counters[0](); // 6
counters[0](); // 7
counters[1](); // 6

Here is a real-life example of things going wrong due to this: setTimeout in for-loop does not print consecutive values 以下是由于这个原因出错的现实例子: for循环中的setTimeout不会打印连续值

Since JavaScript 1.7 you can use the let keyword (see MDN ) to create true local variables. 从JavaScript 1.7开始,您可以使用let关键字(请参阅MDN )来创建真正的局部变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM