Nigel
Nigel

Reputation: 727

Javascript converting from string to instance name

I have a string representing the name of a tool in a screen painting application (examples: 'pencil', 'marker', 'line', 'rect'). For each tool, I have defined a class to perform that tool's functions (e.g. PencilHandler) and created an instance of it (e.g. pencilHandler = new PencilHandler()). Currently, I use a long switch statement to go from the name of the tool (a string) to the corresponding instance (an object) (e.g. switch(tool) { case 'pencil': return pencilHandler; ...}) and then call a method of the returned instance (e.g. pencilHandler.mousedown(event)).

It would be neater if I could dynamically construct the instance name from the tool name rather than using the switch statement, but I haven't been able to find out how to do this. For instance, tool + 'Handler'[mousedown](event) doesn't work (gives a TypeError).

Upvotes: 0

Views: 43

Answers (1)

Dmitry Reutov
Dmitry Reutov

Reputation: 3032

collect them in one object and call by key name

const classesCollection = { PencilHandler, ErazerHandler, BrushHandler }
const requiredClass = classesCollection[tool + 'Handler]

Upvotes: 1

Related Questions