Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to instantiate a javascript class from a dynamic variable?

I'm wondering if I can do something like the following in Javascript:

  1. Have a set of ES6 classes that I have defined (we'll call these components)
  2. Have a function where I pass the name of the class and then within the function I instantiate a new class based on the argument that was passed
  3. Do stuff with the new instantiated class

So if I have some code like the following in a components.js file:

export class ComponentOne {}

export class ComponentTwo {}

export class ComponentThree {}

Then in another file I have the following code:

import {ComponentOne, ComponentTwo, ComponentThree} from './components';

function addComponentToEntity(componentId, entityId) {
  //componentId is the name of the Class that needs to be instantiated
  let comp = new componentId;

  //Do stuff with the newly instantiated class and add it to the entity
}

Is it possible to instantiate a class from a variable like I've outlined above? Or what is the correct way of doing this?

Thank you for your help!

like image 601
Zigrivers Avatar asked Aug 10 '26 23:08

Zigrivers


1 Answers

If you do..

import components from './components';

components will now be an object containing a property for each export within the components.js file.

So you can either do..

var c1 = components.ComponentOne // or...
var c1 = components['ComponentOne']

So you can do this: (from your example)

import components from './components';

function addComponentToEntity(componentId, entityId) {
  //componentId is the name of the Class that needs to be instantiated
  let comp = new components[componentId];

  //Do stuff with the newly instantiated class and add it to the entity
}
like image 177
André Pena Avatar answered Aug 13 '26 12:08

André Pena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!