有几种方法可以实现这一目标......
1.代理类根据@ thefourtheye维护名称到类的映射的示例,您可以拥有一个类,其作用是获取所需类的名称并代理其实例化:
[ 见工作 ]
定义你的课程
// ClassOne.js export class ClassOne { constructor () { console.log("Hi from ClassOne"); } } // ClassTwo.js export class ClassTwo { constructor (msg) { console.log(`${msg} from ClassTwo`); } }
定义代理类(例如DynamicClass
)
import ClassOne from './ClassOne'; import ClassTwo from './ClassTwo'; // Use ES6 Object Literal Property Value Shorthand to maintain a map // where the keys share the same names as the classes themselves const classes = { ClassOne, ClassTwo }; class DynamicClass { constructor (className, opts) { return new classes[className](opts); } } export default DynamicClass;
用法示例
import DynamicClass from './DynamicClass'; new DynamicClass('ClassOne'); //=> "Hi from ClassOne" new DynamicClass('ClassTwo', 'Bye'); //=> "Bye from ClassTwo"2.工厂功能
使用一个函数对类名对象 - >类映射执行查找,并返回对类的引用,然后我们可以像往常一样实例化.
定义工厂功能
import ClassOne from './ClassOne'; import ClassTwo from './ClassTwo'; const classes = { ClassOne, ClassTwo }; export default function dynamicClass (name) { return classes[name]; }
用法示例
import dynamicClass from './dynamicClass' const ClassOne = dynamicClass('ClassOne') // Get the ClassOne class new ClassOne(args) // Create an instance of ClassOne
将类存储在Object中,键是您希望它们成为的类的名称.
const classesMapping = { 'One': ClassOne, 'Two': ClassTwo };
然后根据这样的键名创建类
return new classesMapping[desiredSubclassName](args);