阅读Crockfords JavaScript样式的元素我注意到他更喜欢定义这样的变量:
var first='foo', second='bar', third='...';
Run Code Online (Sandbox Code Playgroud)
如果该方法有任何好处,那么:
var first='foo';
var second='bar';
var third='...';
Run Code Online (Sandbox Code Playgroud)
显然,后者需要更多的打字,但除了美学外,我想知道是否通过定义前一种风格获得了性能优势.
CMS*_*CMS 11
除了美学和下载足迹之外,另一个原因可能是该var
声明需要提升.这意味着无论变量放置在函数中的哪个位置,它都会移动到定义它的作用域的顶部.
例如:
var outside_scope = "outside scope";
function f1() {
alert(outside_scope) ;
var outside_scope = "inside scope";
}
f1();
Run Code Online (Sandbox Code Playgroud)
获取解释为:
var outside_scope = "outside scope";
function f1() {
var outside_scope; // is undefined
alert(outside_scope) ;
outside_scope = "inside scope";
}
f1();
Run Code Online (Sandbox Code Playgroud)
因此,以及只有JavaScript具有的函数范围,这就是为什么Crockford建议在单个语句中声明函数顶部的所有变量var
,以类似于实际执行代码时真正发生的事情.
归档时间: |
|
查看次数: |
1676 次 |
最近记录: |