4

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?

1
  • 1
    Is it going to be a string? Why not pass a reference to the constructor function instead? Commented Jun 1, 2017 at 21:57

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.