简体   繁体   English

Node.js全局变量和使用Require

[英]Node.js Global Variables and using Require

Many people have suggested using "modules" that "export" an object, so that you can bring in variables to another file - because once you require a certain file name once, all future calls in other files to require that same file will immediately return the SAME exported object that was given the first time that file was required without reevaluating any code. 很多人建议使用“导出”对象的“模块”,以便可以将变量引入另一个文件-因为一旦需要一个特定的文件名,以后在其他文件中要求该文件的所有调用将立即返回SAME导出的对象,该对象是首次需要该文件而没有重新评估任何代码的对象。 This allows you to choose by requiring files which variables you want to share between files without using global, which is essential to maintaining state between files or split up code which needs to use the same variables. 这使您可以通过要求文件来选择要在文件之间共享的变量,而无需使用全局变量,这对于维护文件之间的状态或拆分需要使用相同变量的代码至关重要。

My problem is: How can you modify those exported variables - or are they unchangeable - and if they are unchangeable then they are lacking functionality that you can only achieve using global variables... ? 我的问题是:如何修改这些导出的变量-或者它们是不可更改的-如果它们不可更改,则它们缺少只能使用全局变量才能实现的功能...?

There are no such things as exportable variables. 没有可导出变量之类的东西。 The require function returns a usual Javascript object, and things you call "exported variables" are just properties of that returned object. require函数返回一个普通的Javascript对象,您所谓的“导出变量”只是该返回对象的属性。

Internally, require() maintains a dictionary mapping module identifiers to these objects and guarantees that the same object is returned for the same module identifiers passed to it. 在内部, require()维护一个字典映射到这些对象的模块标识符,并确保为传递给它的相同模块标识符返回相同的对象。

So you can modify those properties how you want. 因此,您可以根据需要修改这些属性。 You can even do things like this: 您甚至可以执行以下操作:

var connect = require('connect')
connect.foo = 42

This code will effectively monkey-patch connect module and add foo "export" to it. 此代码将有效地猴子连接模块,并添加foo “出口”到它。

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

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