Javascript 将环境传递给模块

Javascript 将环境传递给模块,javascript,node.js,Javascript,Node.js,我非常习惯Lua,在那里你可以做到这一点,所以请原谅,如果这是不可能的 假设在client.js上有2个变量,这两个变量都需要模块 var EmbedManager = require('Embed'); var client = require('Client'); new EmbedManager() .init() .output() 从模块'Embed'中,我需要能够访问变量'client',而无需将任何内容作为参数传递 例如,文件是这样存储的 Client.js

我非常习惯Lua,在那里你可以做到这一点,所以请原谅,如果这是不可能的

假设在client.js上有2个变量,这两个变量都需要模块

var EmbedManager = require('Embed');
var client       = require('Client');

new EmbedManager()
  .init()
  .output()
从模块'Embed'中,我需要能够访问变量'client',而无需将任何内容作为参数传递

例如,文件是这样存储的

Client.js
Embed.js

如果要从另一个模块访问变量,则需要在
模块中包含该变量。导出
,然后需要该模块

因此,在
Client.js
中,您需要添加一行,如:

// This creates a new exported variable on Client
module.exports.client = client
然后在
Embed.js
中,您需要:

// When you import `Client.js`, you're getting whatever
// it `module.exports`
var Client = require("./Client.js")
// So now we can access the `client` variable of the `Client` module
var client = Client.client

为CommonJS模块格式找到好的文档是非常困难的,但这篇文章并不太糟糕:.

在node js中,如果不想传递参数,首先要考虑的是在
embed.js
文件中只需要
Client
,但这会导致循环依赖性问题。作为
client.js
包括
embed.js
,反之亦然

通常最好的处理方法是以一个文件的方式重新构造模块,该文件同时使用
client.js
embed.js
,因此您可能需要创建
.js
,然后同时需要
client.js
embed.js
,并在该文件中添加逻辑

thirdFile.js

var EmbedManager = require('Embed');
var client       = require('Client');

new EmbedManager().init().output()

new Client().init()

//rest of logic here!

因此,要么使用参数,要么构造代码,在一个文件中使用这两个模块。你不能。争论有什么不对?