在Node.js中,当“需要"时我是否要创建一个新对象? [英] In Node.js, am I creating a new object when "Require"?

查看:95
本文介绍了在Node.js中,当“需要"时我是否要创建一个新对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我不确定那是什么.如果在 ModuleA 中,我有:

So, what I'm not sure is that. if in ModuleA, I have:

var mongoose = require('mongoose');
mongoose.connect(pathA);

ModuleB 中,我有:

var mongoose = require('mongoose');
mongoose.connect(pathB);

在主程序中,我有:

var mA = require('./moduleA.js'), 
mB = require('./moduleB.js');

因此,当我运行主程序时,我想我将创建两个猫鼬实例";一个连接到pathA和一个连接到pathB,对吗?

So, when I run the main program, I guess I will create two mongoose "instances"; one connecting to pathA and one connecting to pathB, is that right?

此外,在模块B中,在我连接到路径B之前,它是否连接到路径A还是什么都没有?

Also, in Module B, before I connect to pathB, is it connected to pathA or nothing?

谢谢.

推荐答案

我刚刚对最新的节点V0.4.6做了一些测试.我确认了以下内容:

I just did a couple of tests with the latest node V0.4.6. I confirmed the following:

  1. 从"require"返回的变量是单例.
  2. 随后的更改将更改所需模块的数据,其中包括该模块的所有其他模块.
  3. 猫鼬的联系有点奇怪.即使断开连接并将其设置为新的连接路径,它仍会使用旧的连接路径.

因此,我对以上第1点和第2点的意思是:

So, what I mean by the above points 1 and 2 is:

如果您有 Module Master :

var myStr = 'ABC';
module.exports.appendStr = function(data) {
    myStr += ' ' + data;    
};
module.exports.output = function() {
    console.log("Output: " + myStr);
};

如果还有其他两个模块:

And if you have two other modules:

模块A

var mc = require('./moduleMaster.js');
var ma = function() {mc.appendStr(' MA '); };
ma.prototype.output = function() {
  mc.output();
}
module.exports.create = function() {
    return new ma();
};

module.exports._class = ma;

模块B

var mc = require('./moduleMaster.js');
var mb = function() {mc.appendStr(' MB '); };
ma.prototype.output = function() {
  mc.output();
}
module.exports.create = function() {
    return new mb();
};

module.exports._class = mb;

现在,当您运行同时需要模块A和模块B的测试脚本时,将它们实例化并输出:

Now when you run a test script that requires both Module A and Module B, instantiate them and output:

mTestA.output();
mTestB.output();

您将获得以下输出:

ABC MA
ABC MA MB

代替

ABC MA
ABC MB

因此,它是一个单例.不仅限于模块本地.

Therefore, it is a singleton. not just local to the module.

这篇关于在Node.js中,当“需要"时我是否要创建一个新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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