简体   繁体   English

你应该在全局范围内使用“var”还是“let”?

[英]Should you use 'var' or 'let' in the global scope?

Let's say I have this express application and want to add a global variable at the top假设我有这个快速应用程序并想在顶部添加一个全局变量

import express from 'express';

const app = express();

// var globalScopeVariable = 123;

app.get('/', (req, res) => {
  // home page
});

app.get('/create/:message', (req, res) => {
  //  add block
});

app.get('/add/:peerPort', (req, res) => {
  // add peer
});

Would it be good practice to use 'var' or 'let' in this scenario?在这种情况下使用“var”或“let”是个好习惯吗?

In your case (Node.js), neither var nor let make a global scope variable;在您的情况下(Node.js), varlet都不能创建全局范围变量; both will create a module-scope variable (accessible inside this module, but not in other modules).两者都将创建一个模块范围变量(可在此模块内访问,但不能在其他模块中访问)。 This may be what you want (in which case, let is generally preferred these days, and var should be consigned to history);这可能是您想要的(在这种情况下,现在通常首选let ,并且var应归入历史记录); but it case it isn't, the only way to make a true global scope variable is by direct assignment:但如果不是,创建真正的全局范围变量的唯一方法是直接赋值:

global.globalScopeVariable = 123;

If your variable can be reassigned, then use let otherwise use const .如果您的变量可以重新分配,则使用let否则使用const You don't have to bother about var anymore.您不必再为var烦恼了。

You can always consider the following powerful master rules around variable declaration in modern JavaScript.您始终可以考虑以下有关现代 JavaScript 中变量声明的强大主规则。

  • Stop using var as soon as you can!尽快停止使用var
  • Use const whenever you can!尽可能使用const
  • Use let only when you really have to!仅在确实需要时才使用let

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

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