gpt4 book ai didi

javascript - 是否可以从动态变量实例化 javascript 类?

转载 作者:行者123 更新时间:2023-11-29 15:30:35 24 4
gpt4 key购买 nike

我想知道我是否可以在 Javascript 中执行以下操作:

  1. 有一组我定义的 ES6 类(我们称这些为组件)
  2. 有一个函数,我在其中传递类的名称,然后在函数中根据传递的参数实例化一个新类
  3. 用新的实例化类做事

因此,如果我在 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
}

是否可以像我上面概述的那样从变量实例化一个类?或者这样做的正确方法是什么?

感谢您的帮助!

最佳答案

如果你这样做..

import components from './components';

components 现在将是一个对象,其中包含 components.js 文件中每个 export 的属性。

所以你可以做..

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
}

关于javascript - 是否可以从动态变量实例化 javascript 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35327012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com