Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Using a variable as a constructor name [duplicate]

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?

like image 264
Maxim Webb Avatar asked Nov 16 '25 01:11

Maxim Webb


1 Answers

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);
like image 76
Pankaj Shukla Avatar answered Nov 18 '25 14:11

Pankaj Shukla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!