0

You can use bracket notation to fetch an object:

var items = {};
items.obj1 = {};

var type = 'obj1';
var myFunc = function(type){
    var newObj = items[type]; //returns items.obj1
};

How can you do the same to dynamically create an object using constructor functions?

var Constructor1 = function() {};
var Constructor2 = function() {};

var type = 'Constructor2';
var myFunc = function(type){
   var newObj = new type(); // how do you invoke either constructor?
};
Data
  • 1,337
  • 11
  • 17

1 Answers1

1

In your example, try the following:

var myFunc = function(type) {
  return new window[type]();
}
flamingcow
  • 341
  • 2
  • 7
  • thanks for your answer, it seems similar to this https://stackoverflow.com/a/969756/1837472; I'll have a play. – Data Jun 10 '14 at 00:52