0

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).

1
  • 3
    You want to store your instances in a Map by their name. Commented Jun 16, 2020 at 13:34

1 Answer 1

1

collect them in one object and call by key name

const classesCollection = { PencilHandler, ErazerHandler, BrushHandler }
const requiredClass = classesCollection[tool + 'Handler]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.