module === 实例
发布于 9 年前 作者 countcain 3850 次浏览 最后一次编辑是 8 年前 来自 问答

我有如下一个 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


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

6 回复


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.


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

module.exports = test;

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

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

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