node.js标准模块的全局变量? [英] Global variables for node.js standard modules?

查看:114
本文介绍了node.js标准模块的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道全局变量很糟糕。

但是如果我在框架中的40个文件中使用节点的模块util,是不是更好?将其声明为一个全局变量,如:

  util = require('util'); 

在index.js文件中,而不是在40个文件中写入该行?



原因我经常在每个文件中使用相同的5-10个模块,这样可以节省大量时间,而不是始终复制粘贴。



在这种情况下,DRY不是很好吗?每个模块都应该是独立的。 在每个模块的第一个模块之后,这个require不需要花费任何东西。

如果你想单独测试一个模块,该怎么办?你会遇到很多问题,因为它不能识别你的应用中有一些全局要求。



是的,全局变量很糟糕,即使在这个案例。 Globals几乎总是会毁灭:可测试性,封装和易于维护。

更新后的答案2012年1月



全局对象现在是每个模块中的全局对象。因此,每次在模块内部分配一个全局变量(无范围)时,该变量将成为该模块的全局对象的一部分。



因此全局对象仍然不是全局,因此不能这样使用。



2012年12月更新



全球对象现在在应用程序中具有全局作用域,并且可用于存储需要从所有模块访问的任何数据/函数。


I know that global variables are bad.

But if I am using node's module "util" in 40 files in my framework, isn't it better to just declare it as a global variable like:

util = require('util');

in the index.js file instead of writing that line in 40 files?

Cause I often use the same 5-10 modules in each file, that would save a lot of time instead of copy paste all the time.

Isn't DRY good in this case?

解决方案

Each module is supposed to be independent. The require doesn't cost anything anyways after the first one for each module.

What if you wanted to test one module alone? You'd be having a lot of issues because it wouldn't recognize some "global" requires that you have in your app.

Yes, globals are bad, even in this case. Globals almost always ruin: testability, encapsulation and ease of maintenance.

Updated answer Jan. 2012

The global object is now a global inside each module. So every time you assign to a global variable (no scope) inside a module, that becomes part of the global object of that module.

The global object is therefore still not global, and cannot be used as such.

Updated Dec. 2012

The global object now has the global scope within the application and can be used to store any data/functions that need to be accessed from all modules.

这篇关于node.js标准模块的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆