在 NodeJS 中“需要”一个模块时,const 和 var 之间是否存在效率差异

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

Is there an efficiency difference between const vs var while 'requiring' a module in NodeJS

node.js

提问by Hugo

I was reading the documentation for https://github.com/rvagg/bland I noticed that, in the examples, they use constto require a module and this made me wonder: is this a good practice? I mean, to me, this looked as a good idea.

我正在阅读https://github.com/rvagg/bl的文档,我注意到,在示例中,他们使用const来要求一个模块,这让我想知道:这是一个好习惯吗?我的意思是,对我来说,这看起来是个好主意。

A direct example from the link above is:

上面链接中的一个直接示例是:

const BufferList = require('bl')

var bl = new BufferList()
bl.append(new Buffer('abcd'))
bl.append(new Buffer('efg'))
/*...*/

I also noticed the lack the semicolons in the example but well, that has been discussed elsewhere thoroughly.

我还注意到示例中缺少分号,但是,这已经在其他地方进行了彻底的讨论。

采纳答案by helpermethod

The constmakes perfect sense here:

const这里很有意义:

  • It documents that the objectreference is not going to change.
  • It has block scope (same as let) which also makes sense.
  • 它记录了对象引用不会改变。
  • 它具有块作用域(与 相同let),这也很有意义。

Other than that it comes down to personal preference (using var, letor const)

除此之外,它归结为个人喜好(使用var,letconst