如果我创建了两个模块,它们都需要 'http' 模块,而我的主应用程序需要这两个模块,或者需要进一步需要这两个模块的模块,同时还需要 'http' 模块来实现自己的目的,那么我最终会有三个 http 模块实例吗?它们是否被锁定在不同的闭包作用域内,或者 node 会重写以避免这种情况?
换句话说,我最终会得到一个具有:
// main app creates a closure containing a local instance of http, an instance of proxy1
// and an instance of proxy2, both of which are functions returned from closures that have instances of http in scope
var http = require('http'),
httpProxy1 = require('./proxy1'),
httpProxy2 = require('./proxy2');
/* ... do stuff with http, using proxy1 or proxy2 where appropriate ... */
// proxy1 creates a closure containing a local instance of http and exposes a single public method
var http = require('http');
module.exports = function (foo) { /* ... do stuff with http ... */ }
// proxy2 creates a closure containing a local instance of http and exposes a single public method
var http = require('http');
module.exports = function (foo) { /* ... do stuff with http that has nothing to do with the stuff proxy1 does ... */ }
如果我还想单独使用proxy1,将其作为一个模块是有意义的,但即使在小型项目中,这也可能导致许多模块反复要求所有核心模块,特别是http和fs。