javascript - 如何根据字符串值实例化对象
问题描述
我有一个字符串,我想在 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
andswitch
语句,因为我有一堆不同的 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]
}
推荐阅读
- linux - wget URL中的多括号扩展
- python - 在 Amazon Redshift 中创建 Python 2.7 UDF 以在 Postgres 上执行
- leaflet - 在 Wikidata 查询服务中排序地图图例项
- php - 如何删除 .htaccess 中的 Google Adwords gclid 查询字符串?
- javascript - 如何从另一个上层目录快速提供静态文件?
- c++ - C++ - thread_local 向量导致 MinGW 上的 join() 崩溃
- android - “android.view.View 已弃用” - 还有什么要使用或如何修复?
- c++ - C ++:(不重复)积分静态成员初始化(不只是声明!)在类中导致链接器错误,为什么?
- django - 使用modelform时视图不显示
- dialogflow-es - 如何使用他们的 REST API 在 DialogFlow 上创建机器人?