Javascript 如何基于字符串值实例化对象

Javascript 如何基于字符串值实例化对象,javascript,reactjs,class,ecmascript-6,ecmascript-2016,Javascript,Reactjs,Class,Ecmascript 6,Ecmascript 2016,我有一个字符串,我想在API工厂中使用它来实例化类中的正确对象。代码如下: import StoryApiService from './story' import AssignmentApiService from './assignment' let apiTypes = { story: null, assignment: null } let token const getApi = (newToken, apiType = 'story') => {

我有一个字符串,我想在API工厂中使用它来实例化类中的正确对象。代码如下:

import StoryApiService from './story'
import AssignmentApiService from './assignment'

let apiTypes = {
    story: null,
    assignment: null
}
let token

const getApi = (newToken, apiType = 'story') => {
    const isNewToken = newToken => newToken !== token
    const shouldCreateService = !apiTypes[apiType] || isNewToken

    if( shouldCreateService ) {
        const capitalizedServiceType = apiType.charAt(0).toUpperCase() + apiType.slice(1)

        // this line is what I need help with
        apiTypes[apiType] = new `${capitalizedServiceType}ApiService`(token)
    }
    return apiTypes[apiType]
}
因此,基本上,根据传入的
apiType
参数,我想从正确的类实例化一个新对象。如果可能的话,我想避免使用
if/else
switch
语句,因为我将使用一系列不同的apiServices,我认为如果可能的话,这种方法会更干净


我知道上面代码中的行不会像写的那样工作,但是它的伪代码显示了我想要达到的效果。

执行与您已经在使用apiTypes[apiType]时执行的相同操作。:访问包含该类/构造函数的对象

例如,如果是您在
窗口中定义的类
范围:

const ObjectType = window[`${capitalizedServiceType}ApiService`];
然后,请记住验证是否已定义,因为无法保证字符串实际映射到函数或类:

if (ObjectType) {
  apiTypes[apiType] = new ObjectType(token);
} else {
  console.error(`Api service for "${capitalizedServiceType}" does not exist.`);
}

创建一个对象,将
apiType
名称直接映射到相应的类,而不是尝试从字符串名称(使用一些复杂的大写/串联逻辑)实例化类:

import StoryApiService from './story'
import AssignmentApiService from './assignment'

const services = {
    story: StoryApiService,
    assignment: AssignmentApiService,
}
const serviceInstances = {
    story: null,
    assignment: null,
}
let token

const getApi = (newToken, apiType = 'story') => {
    const isNewToken = newToken !== token
    const shouldCreateService = !serviceInstances[apiType] || isNewToken

    if (shouldCreateService) {
        token = newToken
        serviceInstances[apiType] = new services[apiType](token)
    }
    return serviceInstances[apiType]
}

听起来你在问React中的依赖注入。我会在这上面搜索一下。看起来好像它已经失宠了,所以YMMV。太棒了,这是完美的,正是我所需要的。非常感谢。