Skip to content
Advertisement

Call a function “dynamically” in JS with something like

I’m trying to learn how to dynamically create objects and apply functions to them with JS and HTML. How can I use a <select> dropdown’s text/value to call a function on an object as directly as possible? In the past I’ve used functions in an array, if then statement, or conditional chain but this seems like extra work.

I’m open to suggestions on dynamic object instance creation as well because I’m not sure my method in this example is best practice.

Here is my example:

HTML

JavaScript

JS

JavaScript

Description: I can create a new object instance of myClass dynamically by typing a name into the name <input> but I would like to do a similar approach with the <select> and the prototypical functions of myClass.

Advertisement

Answer

JavaScript
JavaScript

Try this one.

But there is something to consider. You don’t need to add a seperate `add new object` button. A new instance can be created when you select whether to sum or multiply.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement