我在 Javascript 中定义了一些变量:
var aaa = "aaa";
var bbb = "bbb";
var ccc = "ccc";
但是我的 friend 说最好把它们定义为:
var aaa = "aaa",
bbb = "bbb",
ccc = "ccc";
因为 JsLint 会报告我的代码错误。
我不确定为什么我们应该把它作为第二个,因为我发现如果值很大,我的版本会更好看,比如:
var aaa = {
some1 : 111,
some2 : 222
};
var bbb = {
some1 : 111,
some2 : 222
};
在 JavaScript 中没有 block 作用域,只有函数级作用域。因此,如果您使用多个 var
语句,来自其他语言的开发人员可能感觉不到差异。例如,
var numbers = [];
for (var i = 0; i < 10; i += 1) {
numbers.push(i);
}
如果您熟悉 C、C++ 或 JAVA,您可能会认为 i
在 for
循环之外不可用。但它是,因为第一行提到的原因。
因此,为了避免混淆,JSLint 鼓励您在每个函数中只使用一个 var
语句,而且它也应该是该函数的第一行。
引自jslint's documentation ,
In many languages, a block introduces a scope. Variables introduced in a block are not visible outside of the block.
In JavaScript, blocks do not introduce a scope. There is only function-scope. A variable introduced anywhere in a function is visible everywhere in the function. JavaScript's blocks confuse experienced programmers and lead to errors because the familiar syntax makes a false promise.
JSLint expects blocks with function
, if
, switch
, while
, for
, do
, and try
statements and nowhere else.
In languages with block scope, it is usually recommended that variables be declared at the site of first use. But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. It is recommended that a single var statement be used per function. This can be declined with the vars
option.