简体   繁体   English

在Node.js中声明变量的最佳方法

[英]Best way to declare variables in Node.js

Is it good to declare one variable per var statement, it makes code easier to re-order the lines in the program as per modification needs. 每个var语句声明一个变量是否var ,它使代码更容易根据修改需要重新排序程序中的行。

Could somebody make out, is there any difference between following style of declarations in Node.js in terms of execution of code? 有人可以说,在执行代码方面,Node.js中的以下声明样式之间有什么区别吗?

//Style 1
var keys = ['foo', 'bar']; var values = [23, 42];

//Style 2
var keys = ['foo', 'bar'], values = [23, 42];

You can have multiple var statements in JavaScript; 您可以在JavaScript中使用多个var语句; this is called hoisting ; 这称为吊装 ; However, because you can run into scoping issues, it's best to use a single declaration in any function. 但是,因为您可能遇到范围问题,所以最好在任何函数中使用单个声明。

It's common to see this style 看到这种风格很常见

var keys   = ['foo', 'bar'],
    values = [23, 42];

In fact, the very reason JavaScript allows you to chain the declarations together is because they should be happening together. 事实上,JavaScript允许您将声明链接在一起的原因是因为它们应该一起发生。

To illustrate a scoping issue: 为了说明范围问题:

f = "check?";

var hello = function () {
  console.log(f);          // undefined
  var f = "nope!";
  console.log(f);          // nope!
};

var hello2 = function () {
  console.log(f);          // check?
  var f2 = "nope!";        // not reusing `f` this time
  console.log(f2);         // nope!
};

hello();
hello2();

At first glance, you'd think the first output would be check? 乍一看,您认为第一个输出会被check? , but because you're using var f inside the function body, JavaScript is creating a local scope for it. ,但因为你在函数体中使用var f ,JavaScript正在为它创建一个局部范围。

To avoid running into issues like this, I simply use a single var declaration :) 为了避免遇到这样的问题,我只使用一个var声明:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM