views:

654

answers:

3

Hi All,

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

+3  A: 

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

CMS
Thanks very much! That worked a treat. The only modification for people who might visit this in the future is that in the ExtJS context if you change the "object" to the ExtJS namespace that is begin used. e.g. "var obj = new Ext.ux['myObject']();" Thanks again!
Stuart
A: 

Should be doable using eval():

var obj = eval("new " + objectType + "()");
Zed
-1 for lazy and dangerous code.
Justin Johnson
For the benefit of all of us, could you elaborate on how this code is lazy, and how is it dangerous?
Zed
+1  A: 

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);
mwilcox