我有两个像这样定义的对象(为了问题简化):
var firstObject = function(){ };
firstObject.prototype.doSomethingFirstObjectsDo();
var secondObject = function(){ };
secondObject.prototype.doSomethingSecondObjectsDo();
Run Code Online (Sandbox Code Playgroud)
接下来我有一个对象管理器,它作为我的主应用程序创建对象的一种接口:
var ObjectManager = function()
{
this.create = {
FIRST:firstObject,
SECOND:secondObject
};
};
ObjectManager.prototype.createObject = function(type)
{
return new this.create[type]();
};
Run Code Online (Sandbox Code Playgroud)
最后使用对象管理器动态创建firstObjects或secondObjects的主应用程序示例:
var MainApplication = function(options)
{
this.objectTypes = options.objectTypes;
this.objManager = new ObjectManager();
};
MainApplication.prototype.createObjects = function()
{
//Iterate through all the types this application needs to create
for (var type in this.objectTypes)
{
var dynamicallyCreatedObject = this.objManager.createObject(type);
//Do Something Else
}
};
Run Code Online (Sandbox Code Playgroud)
这种方法效果很好,但我可以看到一个缺点 - 您需要正式为每个可以创建的对象"类型"定义构造函数的名称. …