title: javascript: dynamically create class instances
body: <p>I am writing an app that has features that can be turned on and off via a <code>config.json</code> that looks something like this:</p>
  
  <pre><code>"appFeatures": {
      "header": {
        "create": true,
        "title": "Here Comes the Sun"
      },
      "imageStrip": {
        "create": false,
        "imageDirectory":  "../data/images",
        "imageDimensions": [288, 162]
      },
      "areaChart": {
        "create": true
      },
      "axes": {
        "create": true
      }
  }
  </code></pre>
  
  <p>For each feature there is already a corresponding class of the same name that implements the feature. I'd like to use the name of the feature to create a new instance of the class. After fetching the <code>config.json</code>, I have code (within a <code>Main.js</code> class) that looks like:</p>
  
  <pre><code>this.features = Object.entries(this.config.appFeatures)
    .filter((entry) =&gt; {
      return entry[1].create === true;
    });
  
  this.features.forEach((feature) =&gt; { this.createFeatureInstances(feature[0]); });
  </code></pre>
  
  <p>And then I try to create instances, a la <code>this.header = new Header()</code>:</p>
  
  <pre><code>  createFeatureInstances(featureName) {
      const className = `${featureName.replace(featureName[0], featureName[0].toUpperCase())}`;
  
      this[`${featureName}`] = new Function(`
        return class ${className} {}
      `)();
  </code></pre>
  
  <p>This creates a new, empty <code>Header</code> class and, I suppose, it's instance. It is not the Header class that I have already written and want to create an instance for. How might I write the <code>createFeatureInstances</code> function so that I can create the instance of each class that corresponds to a feature?</p>
  
  <p><strong>EDIT</strong> Because new features may be added to this app in the future by others, I would like to minimize the times that I hard code which features are available to the app. With my current design, another developer can add another feature by writing a new feature class, importing that class into the Main.js class, and pop the config entries into the config .json without having to touch anything else in the code. For this reason, solutions like this one: <a href="https://stackoverflow.com/questions/34655616/create-an-instance-of-a-class-in-es6-with-a-dynamic-name">Create an instance of a class in ES6 with a dynamic name?</a> won't give me a solution because they rely on having a complete list of the classes that should already exist.</p>