在顶部定义每个变量总是最好的方法吗? [英] Is defining every variable at the top always the best approach?

查看:82
本文介绍了在顶部定义每个变量总是最好的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说在函数顶部定义变量是一种很好的技巧,所以最终不会出现变量提升问题。这个:

I've heard that it is a good technique to define your variables at the top of a function, so you don't end up with variable hoisting problems. This:

// Beginning of file

function something(){
    var a, b, c = 1, d, e;
    // Do something
}

// End of file

是一个很好的例子(当然不包括坏的变量名)。

is a good example (excluding the bad variable names, of course).

我的问题是:这总是最好的方法吗?如果你正在使用很多变量怎么办?他们真的应该只是在一条线上吗?

My question is: Is this always the best approach? What if you are working with a lot of variables? Should they really all just be plopped on one line?

推荐答案

我强烈建议给予 Code Complete 2 由Steve McConnell撰写阅读。他的论点是你既不应该在一行中声明所有变量 ,也不应该在例程的顶部声明它们。所以,不要这样做:

I'd highly suggest giving Code Complete 2 by Steve McConnell a read. His argument is that you should neither declare all of your variables in one line, nor should should declare them all at the top of a routine. So, don't do this:

function foo() {
    var a,
        b,
        c,
        d;

     /**
      * 20 lines that use a and b
      */

     /**
      * 10 lines that use c and d
      */
}

相反,你应该声明你的变量关闭到他们需要的地方。在上面的代码中,可能如下所示:

Instead, you should declare your variables close to where they are needed. In the above code, that might look like this:

function foo() {
    var a,
        b;

     /**
      * 20 lines that use a and b
      */

     var c,
         d;

     /**
      * 10 lines that use c and d
      */
}

通过查看上面的声明,您可以快速了解一段代码所使用的变量。您不需要阅读代码来查看设置了哪些变量,只需声明哪些变量。

The benefits are that you can understand at a quick glance what variables are used by a block of code by just looking at the declarations above it. You don't need to read the code to see what variables are set, just which are declared.

不要为编译器或计算机编写代码。写给开发人员。您的代码应尽可能易于阅读,并且需要尽可能少的努力来理解特定的代码部分。

Don't write code for the compiler or for the computer. Write it for developers. Your code should be as easy to read as possible, and require as little effort as possible to understand a particular section of code.

这篇关于在顶部定义每个变量总是最好的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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