简体   繁体   中英

Javascript enums and abstract factory

Recently writing my frontend application i run into problems with enums

const myEnum = Object.freeze({
 fooKey: 'fooValue',
 barKey: 'barValue',
})

then in another part of code i want to use that enum to execute specific action in abstract factory pattern

fooAction(){
 //some-code
}
barAction(){
 //some-code
}
const actionList = {
 fooValue: fooAction,
 barValue: barAction
}
executeAction(enumValue){
 return actionList[enumValue]()
}

is there any nice way to consolidate actionList and myEnum without changing values of myEnum, so that i dont have to hardcode into actionList fooValue and BarValue?

the answear i was looking for is:

const actionList = {
 [myEnum.fooKey]: fooAction,
 [myEnum.barKey]: barAction
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM