Reputation: 169
Is it possible to create an object in Javascript generically from a string class name similar to Java? Maybe some type of Factory?
I want a database to hold a list of class names. Each class name will be associated with a user friendly name. These user friendly names would populate a menu. When a user selects a menu item, the respective class name will be retrieved and the class (object) created. I currently do something similar in Java.
For example, instead of
var obj = new demo.view.CustomObject({});
I would like something like this
var obj = Factory.create('demo.view.CustomObject', params);
Thank you
Upvotes: 0
Views: 575
Reputation: 6308
What you are looking for is using bracket notation to access object properties using a string. Here I have created a factory method that splits the string by dot. Then using array reduce I get into the constructor
function and finally create the object.
function construct(constructorPath, params) {
var constructorFunc = constructorPath.split('.')
.reduce((prev, next) => prev[next], window)
return new constructorFunc(params)
}
// Usage:
var obj = construct('demo.view.CustomObject', someParams)
Upvotes: 1