There is absolutely no difference in meaning or performance, in JavaScript or ActionScript.(在JavaScript或ActionScript中,意义或性能完全没有区别 。)
var
is a directive for the parser, and not a command executed at run-time.(var
是解析器的指令,而不是在运行时执行的命令。) If a particular identifier has been declared var
once or more anywhere in a function body(*), then all use of that identifier in the block will be referring to the local variable.(如果某个特定标识符已在函数体(*)中的任何位置声明为var
一次或多次,则块中该标识符的所有使用都将引用局部变量。) It makes no difference whether value
is declared to be var
inside the loop, outside the loop, or both.(在循环内,循环外或两者中声明value
是否为var
都没有区别。)
Consequently you should write whichever you find most readable.(因此,你应该写出你认为最具可读性的。) I disagree with Crockford that putting all the vars at the top of a function is always the best thing.(我不同意Crockford的说法,将所有变量放在函数的顶部总是最好的。) For the case where a variable is used temporarily in a section of code, it's better to declare var
in that section, so the section stands alone and can be copy-pasted.(对于在代码段中临时使用变量的情况,最好在该部分中声明var
,因此该部分是独立的并且可以进行复制粘贴。) Otherwise, copy-paste a few lines of code to a new function during refactoring, without separately picking out and moving the associated var
, and you've got yourself an accidental global.(否则,在重构期间将几行代码复制粘贴到新函数中,而无需单独挑选和移动相关的var
,并且您自己也是偶然的全局。)
In particular:(尤其是:)
for (var i; i<100; i++)
do something;
for (var i; i<100; i++)
do something else;
Crockford will recommend you remove the second var
(or remove both var
s and do var i;
above), and jslint will whinge at you for this.(Crockford会建议你删除第二个var
(或删除var
和do var i;
上面),然后jslint会向你发出警告。) But IMO it's more maintainable to keep both var
s, keeping all the related code together, instead of having an extra, easily-forgotten bit of code at the top of the function.(但IMO更容易维护两个var
,将所有相关代码保持在一起,而不是在函数顶部有一个额外的,容易被遗忘的代码。)
Personally I tend to declare as var
the first assignment of a variable in an independent section of code, whether or not there's another separate usage of the same variable name in some other part of the same function.(就个人而言,我倾向于在一个独立的代码段中声明为var
变量的第一个赋值,无论是否在同一个函数的某个其他部分中另一个单独使用相同的变量名。) For me, having to declare var
at all is an undesirable JS wart (it would have been better to have variables default to local);(对我来说,必须声明var
是一个不受欢迎的JS wart(将变量默认为local更好);) I don't see it as my duty to duplicate the limitations of [an old revision of] ANSI C in JavaScript as well.(我不认为我有责任在JavaScript中复制[旧版本] ANSI C的限制。)
(*: other than in nested function bodies)((*:除嵌套函数体外)) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…