事情是这样的:
我正在使用 CommonJS 方式使我的移动(iPhone/Android)应用程序模块化。这并不奇怪。但有一件事我就是无法理解。
CommonJS 允许我创建 STATIC 私有变量,这让我可以轻松创建单例。我认为至少这是因为获取的文件内容require()
d 只读取一次,然后每次都会返回导出对象(仅初始化一次)。
但是,当我创建如下所示的循环引用时,每次都会执行包含的模块内的代码。
Wait...有趣的是,当我写这个问题时,我突然意识到没有一个调用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;
I 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
那么为什么像下面这样的循环引用不起作用呢? (我自己可能已经回答过这个问题,如果您愿意,可以评论/回答)。
app.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)