javascript - 为什么要用一个 `var`来定义很多变量呢?

标签 javascript

<分区>

我在 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,您可能会认为 ifor 循环之外不可用。但它是,因为第一行提到的原因。

因此,为了避免混淆,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.

关于javascript - 为什么要用一个 `var`来定义很多变量呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25113690/

相关文章:

javascript - 模型未在 Backbone.js 中渲染

javascript - 通过多个 Action 类型来约束 reducer

javascript - 如何根据类型字符串在 javascript 中创建新对象?

javascript - 使用 MongoDB/Mongoose 在 Node 中执行 HTTP POST 请求?

javascript - 如何使用 Canvas 制作扫描仪效果线动画

javascript - 在 onclick 中传递动态对象 - JavaScript/jQuery

javascript - 最好是 `mainApp.config([' $routeProvider', function($routeProvider )` and ` mainApp.config(function($routeProvider)`

javascript - 使用 jquery 加载页面后清除 <a> href

javascript - jquery扩展和调整大小问题

javascript - Promise.all() 中的 then 子句何时运行?