我有一个字符串,我想在 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 我会使用,我认为如果可能的话这种方式会更干净.
我知道上面代码中的行不会像写的那样工作,但它的伪代码显示了我想要达到的效果。
最佳答案
与其尝试从字符串名称实例化一个类(使用一些复杂的大写/连接逻辑),不如创建一个将 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/