【发布时间】:2014-01-26 04:59:32
【问题描述】:
第一个使用 Node.js 的应用程序,尝试在单例类中探索文件以从中获取内容,但顺序不是我所期望的。我肯定缺少一个知识,你能告诉我为什么..
单例类:
var Singleton = (function()
{
var _instance = null;
return new function()
{
this.Instance = function()
{
if (_instance == null)
{
_instance = new Foo();
}
return _instance;
}
};
})();
Foo 类:
var Foo= function Foo()
{
this._filesDir= "./core/files/";
this._storedFiles = {};
this.method1();
console.log("call constructor");
};
Foo.prototype = {
method1: function()
{
console.log("call method1");
var that = this;
var c = 0;
fs.readdirSync(this._filesDir).forEach(function(fileName)
{
console.log("iterating file"+ c);
c++;
fs.readFile(that._filesDir + fileName, 'utf-8', function(err, content)
{
var clean_FileName = fileName.replace(".txt", "");
console.log( clean_fileName );
that._storedFiles[ clean_fileName ] = content;
});
});
},
method2: function( fileName )
{
console.log('call method2');
return ( fileName in this._storedFiles);
}
};
呼唤:
console.log( Singleton.Instance().method2("myfile") );
目录中只有这个myfile.txt
但是,控制台向我显示:
call method1
iterating file0
call constructor
call method2
false
GET /test 304 11ms
myfile
所以我的回答是错误的,这个普通的构造函数是在第三个位置调用的吗?我需要类构造、存储并最终执行method2()。我做错了什么?
【问题讨论】:
标签: javascript node.js singleton