声明空 javascript 变量的最佳实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16912892/
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-27 06:26:13  来源:igfitidea点击:

Best practice for declaring empty javascript variables

javascript

提问by Hendrik

Is there something like a best practise when it comes to declaring variables in javascript before assigning a value to them? Sometimes it's necesary for scope reasons, but what if scope doesn't matter?

在为它们分配值之前在 javascript 中声明变量时,是否有类似的最佳实践?有时出于范围原因它是必要的,但如果范围无关紧要怎么办?

// Declare first
(function() {
    var foo = 'bar',
        a = 500,
        b = 300,
        c;

    // Some things get done here with a and b before c can use them...

    c = a * b;    

    // c is now ready to use...
    doSomething(c);
}());

// Declare when needed
(function() {
    var foo = 'bar',
        a = 500,
        b = 300;

    // Some things get done here with a and b before c can use them...

    var c = a * b; 

    // c is now ready to use...
    doSomething(c);
}());

And I'm also wondering what's best practise for something similar with object literals:

而且我还想知道与对象文字类似的东西的最佳实践是什么:

// Add property with null assigned to it
var myObj = {
    foo: null,

    doSomething: function() {
        this.foo = 'bar';
    }
};

// Property gets added when value is set
var myObj = {
    doSomething: function() {
        this.foo = 'bar';
    }
};

采纳答案by Fabrício Matté

It is mostly a matter of style.

这主要是风格问题。

As vardeclarations are automatically hoisted upto the top of the scope, it makes sense to place them at top of their scope so that you can read the code closer to how the interpreter will execute it.

由于var声明会自动提升到作用域的顶部,因此将它们放在作用域的顶部是有意义的,这样您就可以更接近解释器将如何执行它来阅读代码。

Declaring variables at the top of their scope is Crockford's recommendation. And it does make sense as it clears up some common misconceptions.

在其作用域的顶部声明变量是Crockford 的建议。它确实有道理,因为它消除了一些常见的误解。

For example:

例如:

for (var i = 0; i < 3; i++) {
    setTimeout(function() {
        console.log(i);
    }, 0);
}

Since varhas function scope, all iterations (and functions inside of them) refer to the same i. As all three timed functions will execute after the loop ends, the snippet above logs 3three times.

由于var具有函数作用域,所有迭代(以及其中的函数)都引用相同的i. 由于所有三个定时函数都将在循环结束后执行,因此上面的代码片段记录了33 次。

Now for those with block scoping experience, the above behavior is not very clear. Rewriting the snippet:

现在对于那些有块作用域经验的人来说,上面的行为不是很清楚。重写片段:

var i;
for (i = 0; i < 3; i++) {
    // ...
}

Now, iis declared in the global scope, exactly as the previous snippet. However, this one is much more clear on that.

现在,i在全局范围内声明,与前面的代码片段完全一样。然而,这一点要清楚得多。



Another misconception:

另一个误解:

(function() {
    if (true) {
        var foo = 1;
    } else {
        var foo = 1;
    }
}());

Again, in block-scoped languages1 the above is perfectly valid. However, as vardeclarations are hoisted up to top of the current function scope at parse time, the above is equivalent to:

同样,在块范围语言1中,上述内容完全有效。然而,由于var声明在解析时被提升到当前函数作用域的顶部,所以上面的等价于:

(function() {
    var foo;
    var foo;
    if (true) {
        foo = 1;
    } else {
        foo = 1;
    }
}());

The variable is declared twice. Most browsers will just ignore the second declaration and the code will "work", but static code analysis tools such as JSHintwill yell at you.

变量声明了两次。大多数浏览器会忽略第二个声明,代码会“工作”,但静态代码分析工具如JSHint会冲你大喊大叫。

You can rewrite it with only one declaration and it is perfectly valid:

你可以只用一个声明重写它,它是完全有效的:

(function() {
    if (true) {
        var foo = 1;
    } else {
        foo = 1;
    }
}());

But OCD-like coders like me will find it rather ugly. So again, declaring at top of the scope:

但是像我这样的类似强迫症的程序员会发现它相当丑陋。因此,再次声明在范围的顶部:

(function() {
    var foo;
    if (true) {
        foo = 1;
    } else {
        foo = 1;
    }
}());

Looks much more tidier.

看起来整洁多了。



Again, it is mostly a matter of style. Personally, if I have a giant function, I hate to scroll all the way up just to check whether a variable is already declared and adding it to the list. In that case, I may just add a couple of vardeclarations in the middle of the function (against Crockford's recommendation) which I personally find easier to read and maintain.

同样,这主要是风格问题。就个人而言,如果我有一个巨大的函数,我讨厌一直向上滚动只是为了检查是否已经声明了一个变量并将其添加到列表中。在这种情况下,我可能只var在函数中间添加几个声明(反对 Crockford 的建议),我个人认为这些声明更易于阅读和维护。

As it is a matter of style, just make sure to keep your code the most maintainable and concise possible.

由于这是一个风格问题,因此请确保您的代码尽可能地易于维护和简洁。



In the other side of the coin, I'll admit that, personally, I've started and mostly used vardeclarations when the variable is firstly used. This is an aspect of the language and you can use it this way without problem.

另一方面,我承认,就我个人而言,var当第一次使用变量时,我已经开始并主要使用声明。这是语言的一个方面,您可以毫无问题地以这种方式使用它。

But I will also admit that, if I had followed Crockford's recommendations from the start, I'd have had many less headaches (as with the misconceptions shown above) and would have grasped JavaScript's function scoping aspect much faster.

但我也承认,如果我从一开始就遵循 Crockford 的建议,我的头痛就会少很多(就像上面显示的误解一样)并且会更快地掌握 JavaScript 的函数作用域方面。



1 Note that JS 1.7 introduced block-scoped variables through let, but it is not widely supported yet.

1 请注意,JS 1.7 通过 引入了块作用域变量let,但尚未得到广泛支持。