Question

This may not be possible (or might be dead easy! :) ) so here it is...

I want to be able to create objects of a type that is dependant on a variable set, without the need for a big switch statement.

I think it is possible in PHP to do something like...

$objectType = "myNewClass";
$newObject = new $objectType();

where the $newObject variable will hold an instance of the Class "myNewClass".

Is this (or any similar technique) possible with Javascript?

Thanks Stuart

Was it helpful?

Solution

If your constructor functions are defined in the global scope, you can access it trough the bracket notation (window[fnName]):

function ObjectType1(){  // example constructor function
  this.type = 1;
}


var objectType = 'ObjectType1'; // string containing the constructor function name

var obj = new window[objectType](); // creating a new instance using the string
                                    // variable to call the constructor

See: Member Operators

OTHER TIPS

CMS's answer is good, but in EXT you're probably dealing with namespaces.

I create an object map that holds any dynamic classes:

// within a namespace:
var ns = {
    Thinger: function(){}
};

// globals:
var Zinger = function(){} 

// map:
var classes = {
    zinger:Zinger,
    thinger:ns.Thinger    
};

var type = "thinger";

var myClass = new classes[type](props, type, etc);

Should be doable using eval():

var obj = eval("new " + objectType + "()");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top