David Findlay
David Findlay

Reputation: 1356

JavaScript New Object by Variable

I'm trying to implement polymorphism in Javascript/node.js. I'm trying to do something, but I'm not sure what it's called so I'm not even sure what I'm searching for.

I have a number of different ES6 Classes that are interchangeable and have the same interface. I'm trying to make a system that is extensible and pluginable, so the classes available won't be known at design time.

I want to have a variable which defines the name of the class that I want to create an instance of. So effectively I want to have the following:

class Foo { }
class Bar { }

var classToLoad = "Foo";

var myFoo = new classToLoad;   // I want this to be equivalent to new Foo;

var classToLoad = "Bar";
var myBar = new classToLoad;   // I want this to be equivalent to new Bar;

Can anyone tell me what the name for this is and how to properly do it?

Upvotes: 0

Views: 107

Answers (2)

Estus Flask
Estus Flask

Reputation: 222910

There should be a container to identify classes by their names. Notice that there may be more than one class of same name, and function/class names are minified in client-side scripts.

class Foo { }
class Bar { }

const container = { Foo, Bar };

let classToLoad = "Foo";

let myFoo = new container[classToLoad]();

Upvotes: 3

Arber
Arber

Reputation: 541

This could help:

var Foo = class Foo { }
var Bar = class Bar { }

var classToLoad = "Foo";

var myFoo = new window[classToLoad]();   // I want this to be equivalent to new Foo;

var classToLoad = "Bar";
var myBar = new window[classToLoad]();   // I want this to be equivalent to new Bar;

Upvotes: 0

Related Questions