3

I need to take a parameter from another function which will then be used as the name of the constructor for a new instance of an object:

function foo(bar) {
    thing.push(new bar(arg1, arg2);
}

How do I create a new instance of an object which is constructed by the value of bar, where bar is a string?

Maxim Webb
  • 67
  • 8

2 Answers2

2

You can pass the constructor function.

var Bar = function (a1,a2) {
 this.a1 = a1;
 this.a2 = a2;
}

function foo(bar) {
    
    var obj = new bar('arg1', 'arg2');
    console.log(obj.a1);
    console.log(obj.a2);
}

foo(Bar);
Pankaj Shukla
  • 2,657
  • 2
  • 11
  • 18
1
Use eval() if the string is cleaned of malicious code.
function foo ( bar ) { 
//code to check if bar is safe to use

//if it's not either clean it up or return ; eval("thing . push ( new " + bar + "( arg1 , arg2 );"); } That should work

user7951676
  • 377
  • 2
  • 10