我有如下一个 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在运行时就是个“静态类”。
大家怎么看? 这是我今天写代码时的一个小想法。
怎么看?当然是看文档。
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.