事情是这样的:
我正在使用 CommonJS 方法使我的移动(iPhone/Android)应用程序模块化。那里并不奇怪。但是有一件事我就是想不通。
CommonJS 让我可以创建 STATIC 私有变量,这让我可以轻松创建单例。我认为这至少是因为获取require()
d 的文件的内容只读取一次,然后每次都返回导出对象(仅初始化一次)。
但是当我创建如下所示的循环引用时,每次都会执行包含模块内的代码。
等等......
有趣的是,当我写这个问题时,我突然意识到require()
在下一个开始之前没有一个调用完成(因此下面显示了堆栈溢出)。
关于我是否走上正轨有什么想法吗?这里已经过了凌晨 5 点,所以就我而言,所有的赌注都被取消了:D。
例子:
看这段代码,它定义了一个单例:
/* Singleton.js */
exports.getSingleton = getSingleton;
function getSingleton(name) {
if (!instance) {
instance = new Thing(name);
}
return instance;
}
function Thing(name) {
this.name = name;
}
var instance;
我require()
这个文件是这样的:
var theFirstThing = require('Singleton').getSingleton('first');
Ti.API.info('first: ' + theFirstThing.name)
var possiblyAnotherOtherThing = require('Singleton').getSingleton('second');
Ti.API.info('second: ' + possiblyAnotherOtherThing.name);
输出是:
[DEBUG] loading: /path/to/sim/MyApp.app/app.js, resource: app_js
[DEBUG] loading: /path/to/sim/MyApp.app/Singleton.js, resource: Singleton_js
[INFO] first: first
[INFO] second: first
为什么像下面这样的循环引用不起作用?(我自己可能已经对此进行了分析,如果你愿意,可以评论/回答)。
应用程序.js
require('Banana');
菠萝.js
require('Banana');
香蕉.js
require('Pineapple');
因为输出是这样的:
[DEBUG] loading: /path/to/simulator/MyApp.app/app.js, resource: app_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Banana.js, resource: Banana_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Pineapple.js, resource: Pineapple_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Banana.js, resource: Banana_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Pineapple.js, resource: Pineapple_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Banana.js, resource: Banana_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Pineapple.js, resource: Pineapple_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Banana.js, resource: Banana_js
/* etcetera (total of 15 times back and forth) */
[DEBUG] loading: /path/to/simulator/MyApp.app/Pineapple.js, resource: Pineapple_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Banana.js, resource: Banana_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Pineapple.js, resource: Pineapple_js
[ERROR] Script Error = Maximum call stack size exceeded. (unknown file)