I'm wondering if I can do something like the following in Javascript:
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!
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With