javascript 在顶部定义每个变量总是最好的方法吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5053073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:47:15  来源:igfitidea点击:

Is defining every variable at the top always the best approach?

javascriptvariables

提问by Chris Laplante

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?

我的问题是:这总是最好的方法吗?如果您正在处理大量变量怎么办?他们真的应该全部放在一条线上吗?

回答by ircmaxell

I'd highly suggest giving Code Complete 2by Steve McConnella 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:

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

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.

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

回答by ircmaxell

"Should they really all just be plopped on one line?"

“真的应该把它们都放在一条线上吗?”

I don't think so.

我不这么认为。

Here is how I would write that (ignoring names):

这是我将如何写(忽略名称):

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

This only looks silly in the abovebecause 1) the names suck 2) the variables are not assigned in the "declaration" -- most code can be written with immutable (assigned-once) variables and I find this to simplify code. I use this for multiple reasons including clarity and resistance to formatting changes(that is, I can change the initial values, add/or remove declarations, etc, without mucking about the formatting of the other lines).

在上面看起来很愚蠢,因为 1) 名称很烂 2) 变量没有在“声明”中分配——大多数代码可以用不可变的(分配一次)变量编写,我发现这是为了简化代码。我出于多种原因使用它,包括清晰度和对格式更改的抵抗(即,我可以更改初始值、添加/或删除声明等,而无需考虑其他行的格式)。

"Is defining every variable at the top always the best approach?"

“在顶部定义每个变量总是最好的方法吗?”

I don't think so.

我不这么认为。

For instance, here is how I write loops:

例如,这是我编写循环的方式:

for (var i = 0; i < x; i++) {
  var elm = elms[i];
  ...
}

And some people will go "BUT THE VAR IS HOISTED TO THE TOP OF THE FUNCTION!" or "A VARIABLE IS FUNCTION-SCOPED!". Well, indeed. However, that allows me to easily visuallysee that this is an error, even if the JavaScript engine won't help:

有些人会说“但是 VAR 被提升到了功能的顶部!” 或“变量是函数范围的!”。嗯,确实。但是,这让我可以轻松地直观地看出这是一个错误,即使 JavaScript 引擎无济于事:

for (var i = 0; i < x; i++) {
  var elm = elms[i];
  ...
}
...
// valid JS but since I consider this construct *invalid*
// I know this is a *bug* in my code
alert(elm);

As far as when I assign to variables caught in closures: it depends. If the variable is used in only a single closure I generally put it right above. This lets me know it should only be used in that closure. If the variable is shared (e.g. self) I put it above all the applicable closures -- generally in the "variable declaration section" of the function. This lets me know it has a "function-wide scope" (read: likely to be used in multiple bindings).

至于当我分配给闭包中捕获的变量时:这取决于。如果变量只用在一个闭包中,我通常把它放在上面。这让我知道它应该只在那个闭包中使用。如果变量是共享的(例如self),我将它放在所有适用的闭包之上——通常在函数的“变量声明部分”中。这让我知道它具有“功能范围”(阅读:可能用于多个绑定)。

To address the "for-each closure issue" -- just learn the language. Keeping variable "declarations" close to the closure does not affect this in anyway. If the construct is not understood, it really doesn't matter howthe code is written.

要解决“for-each 闭包问题”——只需学习语言。保持变量“声明”接近闭包无论如何都不会影响这一点。如果结构不被理解,那么代码是如何编写的并不重要。

I use these approaches to/because:

我使用这些方法来/因为:

  1. Have consistent easy-to-scan code.
  2. Write code that tells me when it's wrong.
  3. I prefer code that is amendable to altering without changing structure.
  4. Self-documenting code means less comments.
  5. I like to "read vertically"
  1. 具有一致的易于扫描的代码。
  2. 写代码告诉我什么时候出错了
  3. 我更喜欢可以修改而不改变结构的代码。
  4. 自记录代码意味着更少的注释。
  5. 我喜欢“垂直阅读”

Happy coding.

快乐编码。

回答by Oleg Pavliv

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. This way you don't fool yourself or other people about the variable's scope.

但是因为 JavaScript 没有块作用域,所以在函数顶部声明函数的所有变量是更明智的。这样你就不会在变量的作用域上欺骗自己或其他人。

EDIT: Many people work with several languages simultaneously. Often JavaScript is the only one among them without the block scope.

编辑:许多人同时使用多种语言。通常 JavaScript 是其中唯一没有块作用域的。

回答by Raynos

This is a style question. Not a functionality question.

这是一个风格问题。不是功能问题。

The javascript parser will take this code

javascript 解析器将采用此代码

function() {
   dostuff();
   var i = 4;
}

and turn it into :

并将其变成:

function() {
   var i;
   dostuff();
   i = 4;
}

As for the style question. No thank you I thought we left that behind with ANSI C.

至于风格问题。不,谢谢,我以为我们把它抛在了 ANSI C 后面。

What you want to do is declare functions at the top of their "scope"

您想要做的是在其“范围”的顶部声明函数

If the "scope" of a variable is the entire function then declare them at the top. If the "scope" is a subset of a function then declare them at the start of the subset.

如果变量的“范围”是整个函数,则在顶部声明它们。如果“范围”是函数的子集,则在子集的开头声明它们。

treat "scope" as logical scope rather then function scope.

将“范围”视为逻辑范围而不是函数范围。

This should ensure maximum readability.

这应该确保最大的可读性。

回答by Brad Christie

I would venture to say that in older structures (such as the C\C++ days) it was important to initialize your variables and assign them a start value. But with the way things have been going, I'm finding that declaring them "when necessary" is a valid implementation. Unless scope is playing a part (for instance you need variable anot only in that function, but also in other functions, too), I would declare on-the-go.

我敢说,在较旧的结构中(例如 C\C++ 时代),初始化变量并为其分配起始值非常重要。但随着事情的进展,我发现在“必要时”声明它们是一个有效的实现。除非作用域a在起作用(例如,您不仅需要在该函数中使用变量,还需要在其他函数中使用变量),否则我会声明 on-the-go。

Maybe it's just way of thinking, but I tend to declare things based on scope (If the variable is needed only within an if condition or a few lines of code, I'll declare it there (rather than at the top of my function/class). If I don't go through that code path, I think of it as saving the memory allocation and it won't be declared for "no reason".)

也许这只是一种思考方式,但我倾向于根据范围声明事物(如果仅在 if 条件或几行代码中需要该变量,我会在那里声明它(而不是在我的函数顶部/类)。如果我不通过该代码路径,我认为它保存了内存分配,并且不会“无缘无故”地声明它。)

I could be completely wrong, however. Either way, JavaScript will allow you to declare your variables in any fashion you deem easiest to read.

然而,我可能完全错了。无论哪种方式,JavaScript 都允许您以您认为最容易阅读的任何方式声明变量。

回答by Eli

This is really just a matter of preference. For example, if my method only contains a for loop, then I won't extract the loop variables to the top:

这实际上只是一个偏好问题。例如,如果我的方法只包含一个 for 循环,那么我不会将循环变量提取到顶部:

var func = function(arr) {
    for (var i = 0, len = arr.length; i < len; i++) {
        // array processing here
    }
}

Almost all other times though I will place ALL variables at the top for hoisting reasons. If you find that there are too many variables at the top of your function, it could be an indication that your method is doing too much work, and should consider extracting a portion of it into some sort of helper method. This will let you organize your variables based on functionality.

几乎所有其他时间,尽管出于提升的原因,我都会将所有变量放在顶部。如果您发现函数顶部的变量过多,则可能表明您的方法做了太多工作,应考虑将其中的一部分提取到某种辅助方法中。这将使您可以根据功能组织变量。