module === 实例
发布于 1个月前 作者 countcain 300 次浏览 来自 问答

我有如下一个 module A

var a = 1; module.exports = { setA: function(){ a=2; }, getA: function(){ return a; } };

另外两个module B, C require A B: var Ainstance = require(‘./A’); Ainstance.getA(); //a=1; Ainstance.setA();

C: var Binstance = require(‘./B’); var Ainstance = require(‘./A’); Ainstance.getA(); //a=2

C 中 a 确为2

如此确实可以从某种程度上说module在运行时就是个“静态类”。

大家怎么看? 这是我今天写代码时的一个小想法。

6 回复

怎么看?当然是看文档。

http://nodejs.org/api/modules.html#modules_caching

Modules are cached after the first time they are loaded. This means (among other things) that every call to require(‘foo’) will get exactly the same object returned, if it would resolve to the same file. Multiple calls to require(‘foo’) may not cause the module code to be executed multiple times. This is an important feature. With it, “partially done” objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles. If you want to have a module execute code multiple times, then export a function, and call that function.

所以我这个===不成立。cached会failed。

function test() { var a = 1; console.log(a++); }

module.exports = test;

@undeadway 你的a不是gloable的。我这里讨论的其实是,如何维护一个global的object被众多module共享。

@countcain 这类问题,还是从设计模式下手了…

在A文件里,你把a放在外层会产生闭包,当然会被共享。 主要还是看你的代码怎样写,不一定就说是“静态类”

回到顶部