在JavaScript中单独使用逗号和单独定义变量是否有好处? [英] Is there a benefit to defining variables together with a comma vs separately in JavaScript?

查看:93
本文介绍了在JavaScript中单独使用逗号和单独定义变量是否有好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读Crockfords JavaScript风格的元素我注意到他更喜欢定义这样的变量:

Reading Crockfords The Elements of JavaScript Style I notice he prefers defining variables like this:

var first='foo', second='bar', third='...';

如果该方法有任何好处,那么:

What, if any benefit does that method provide over this:

var first='foo';
var second='bar';
var third='...';

显然后者需要更多的打字但除了美学外,我想知道是否有获得的性能优势通过定义前一种风格。

Obviously the latter requires more typing but aside from aesthetics I'm wondering if there is a performance benefit gained by defining with the former style.

推荐答案

除美学和下载足迹外,另一个原因可能是 var 语句受提升的约束。这意味着无论变量放在函数中的哪个位置,它都会移动到定义它的作用域的顶部。

Aside of aesthetics, and download footprint, another reason could be that the var statement is subject to hoisting. This means that regardless of where a variable is placed within a function, it is moved to the top of the scope in which it is defined.

例如:

var outside_scope = "outside scope";
function f1() {
    alert(outside_scope) ;
    var outside_scope = "inside scope";
}
f1();

获取解释为:

var outside_scope = "outside scope";
function f1() {
    var outside_scope; // is undefined
    alert(outside_scope) ;
    outside_scope = "inside scope";
}
f1();

因此,以及只有JavaScript的函数范围,这就是为什么Crockford建议声明所有函数顶部中的变量在单个 var 语句,类似于实际执行代码时真正发生的事情。

Because of that, and the function-scope only that JavaScript has, is why Crockford recommends to declare all the variables at the top of the function in a single var statement, to resemble what will really happen when the code is actually executed.

这篇关于在JavaScript中单独使用逗号和单独定义变量是否有好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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