Node.js - create object of class name specified in variable

Forseti picture Forseti · Dec 18, 2017 · Viewed 7.7k times · Source

I have a class hierarchy like:

               |-> Square
AbstractShape -+-> Circle
               |-> Triangle

Now, I'd like to implement strategy pattern and create an object of class that's stored in string. In PHP I'd use:

$type = 'Square';
$obj = new $type();

Is there an equivalent in Node.js?

Answer

GaloisGecko picture GaloisGecko · Dec 18, 2017

A safe way would be defining a factory object:

function Square() {
}

// here other constructors for Circle and Triangle   

var factory = {
    "Square": Square,
    "Circle": Circle,
    "Triangle" : Triangle   
}

var typeName;

// here some code which sets typeName

var typeObj = new factory[typeName]();