我想知道我是否可以在Javascript中执行以下操作:
所以,如果我在components.js文件中有如下代码:
export class ComponentOne {}
export class ComponentTwo {}
export class ComponentThree {}
然后在另一个文件中我有以下代码:
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
}
是否可以从像上面概述的变量中实例化一个类?或者这样做的正确方法是什么?
感谢您的帮助!
答案 0 :(得分:1)
如果你这样做..
import components from './components';
components
现在将成为包含export
文件中每个components.js
的属性的对象。
所以你可以做..
var c1 = components.ComponentOne // or...
var c1 = components['ComponentOne']
所以你可以这样做:(来自你的例子)
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
}
答案 1 :(得分:0)
您需要创建一个包含所有名称的对象,因此您可以使用索引器:
import classes from './components'
new classes[componentId];