首页 > 解决方案 > 如何根据字符串值实例化对象

问题描述

我有一个字符串,我想在 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/elseandswitch语句,因为我有一堆不同的 apiServices 我将使用,我认为如果可能的话,这种方式会更干净。

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

标签: javascriptreactjsclassecmascript-6ecmascript-2016

解决方案


与其尝试从字符串名称实例化一个类(使用一些复杂的大写/连接逻辑),不如创建一个将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]
}

推荐阅读