Best way to dynamically create new objects in JavaScript?

I have two objects defining something similar (simplified for the question):

var firstObject = function(){ };
firstObject.prototype.doSomethingFirstObjectsDo();

var secondObject = function(){ };
secondObject.prototype.doSomethingSecondObjectsDo();

Next, I have an Object Manager that works as a kind of interface for my main application for creating objects:

var ObjectManager = function()
{
    this.create = {
        FIRST:firstObject,
        SECOND:secondObject
    };
};

ObjectManager.prototype.createObject = function(type)
{
    return new this.create[type]();
};

Finally, an example of a main application that uses the object manager to dynamically create either firstObjects or 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
    }
};

This approach works fine, but it has one drawback that I can see is that you need to formally define the name of the constructor function for each “Type” object that can be created.

, " ", , " " ObjectManager.

ObjectManager "" :

//Inside MainApplication
for (var type in this.objectTypes)
{
    var dynamicallyCreateObject = new [type]();  //Invalid Syntax
};

- , JavaScript "" ?


:

, .

(function(){
    //All of My Mentioned Code is Found Here
    $(document).ready(function(){
        mainApp = window.mainApp = new MainApplication(options);
    });
});

@casablanca: , , , NameSpace , . , , , , "" - , .

+3
2

, ( , ), window DOM 0 .

var $global = this;
var firstObject = function(){};

var objName = "firstObject";
var instance = new $global[objName];
+4

:

var dynamicallyCreateObject = new [type]();

, , . , , window:

var dynamicallyCreateObject = new window[type]();

, - :

var dynamicallyCreateObject = new MyNamespace[type]();
+7

Source: https://habr.com/ru/post/1775755/


All Articles