javascript - 如何根据字符串值实例化对象

标签 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') => {
    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/elseswitch 语句,因为我有一堆不同的 apiServices 我会使用,我认为如果可能的话这种方式会更干净.

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

最佳答案

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

关于javascript - 如何根据字符串值实例化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57700261/

相关文章:

javascript - CSS/Jquery 如何自动调整容器和图像的大小

javascript - 如何更改 css 背景 onclick

javascript - react 路线与 URL 参数不更新 View

reactjs - MDX - 故事书 + react + typescript

java - 多重继承,在 Java 中使用接口(interface)与使用组合

php - 关闭连接 PDO

javascript - value清空后如何添加回占位符?

javascript - Node.js Promises Q.all 不起作用

javascript - 在更改方法上使用输入子项来 react 控件父级状态

javascript - 在滚动时触发 css animate 类