JavaScript中的每个函数一个var? [英] One var per function in JavaScript?

查看:181
本文介绍了JavaScript中的每个函数一个var?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用JSLint让我对我的JavaScript感到不好。顺便说一下,它很棒。有一张我不太明白的支票,我想请你的意见。

I've been using JSLint to make me feel bad about my JavaScript. It is great, by the way. There is one check that I don't quite understand and I'd like your views, please.

来自 jslint.com


在具有块范围的语言中,通常建议在首次使用的站点声明变量。但是因为JavaScript没有块范围,所以在函数顶部声明所有函数的变量是明智的。 建议每个函数使用一个var语句。

以粗体显示的最后一个发送号是什么真的说?我想我应该声明这样的多个变量?

What is the last sentance in bold really saying? I think I should be declaring multiple variables like this?

var foo = 1, bar = 2;

并且,明智部分只是一种编程风格,可以阻止错误或者是否存在错误还有更多呢?

And, is the "wise" part just a programming style to discourage errors down the line or is there more to it than that?

感谢您的帮助。

推荐答案

问题在于,无论你是否意识到,javascript都会无形地将所有var声明移动到函数范围的顶部。

The problem is that, whether you realise it or not, javascript invisibly moves all the var declarations to the top of the function scope.

所以如果你有一个类似的函数这个

so if you have a function like this

var i = 5;
function testvar () {
     alert(i);
     var i=3;
}
testvar();

警报窗口将包含undefined。因为在内部,它已被改为:

the alert window will contain undefined. because internally, it's been changed into this:

var i = 5;
function testvar () {
     var i;
     alert(i);
     i=3;
}
testvar();

这称为吊装。
crockford如此强烈主张var声明在顶部的原因是它使代码明显与它要做的事情相匹配,而不是允许发生隐形和意外行为。

this is called "hoisting". The reason crockford so strongly advocates var declarations go at the top, is that it makes the code visibly match what it's going to do, instead of allowing invisible and unexpected behavior to occur.

这篇关于JavaScript中的每个函数一个var?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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