Galvani Galvani - 5 months ago 7
Javascript Question

Creating object by using string as a name

My function gets model name as string, I need to create new instance of object based on its name.


modelName = 'MockA';
model = new modelName();

this is ofcourse not working. in php i would use

model = new $$modelName

thanks in advance


If MockA is in global scope you can use:

var model = new window[modelName]();

if not then you should reconsider the way you store your models, eg. with an object of models:

var my_models = {
   MockA: function() {},
   MockB: function() {}

and to access

var MockA = my_models.MockA;
// or
var model_name = 'MockA';
var MockA = my_models[model_name];