CNode

module === 实例

问答
Ccountcain发布于12 年前最后回复12 年前6 回复4698 浏览0 收藏

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

M
microlv#1·12 年前
引用 countcain@undeadway 你的a不是gloable的。我这里讨论的其实是,如何维护一个global的object被众多module共享。

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

J
jysperm#2·12 年前

怎么看?当然是看文档。

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.

C
countcain#3·12 年前

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

U
undeadway#4·12 年前

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

module.exports = test;

C
countcain#5·12 年前
引用 undeadwayfunction test() { var a = 1; console.log(a++); } module.exports = test;

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

参与回复
登录后即可参与回复。登录