0

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

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. Nicely done. Fits the bill perfectly. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.