HomeScienceTechnologyJavaScript: How to Dynamically call method of different objects where method name...

JavaScript: How to Dynamically call method of different objects where method name is computed at run-time

Sometimes we need to call JavaScript function at run time based on the parameters and conditions.  In such cases we cannot directly call the function as we do not have the prior knowledge on Calling Function.
Here’s how we can do it:


Suppose I have two list-boxes one with “Name of Shapes” and the other with “All Properties of Object Shape”
On Selection of “Shape”, all properties will get populated and based on the “Selected Property” method will get call dynamically.


Shapes: Triangle, Square

Property: Color, Label

Pseudo Code:

function setColor(arg1) {  },

function setLabel(arg1) {  }

function setColor(arg1) {  },

function setLabel(arg1) {  }

Selected Values:

selectedShape = Triangle

selectedProperty = Color

// Create Method Name based on Selected Property
var methodName = “set”.concat(selectedProperty);

//create object of selectedShape
var objShape = new selectedShape();

// Call Method dynamically

Hope this will be useful !!!

Pratibha Ramteke
10+ years of experience As Software Development Engineer in Test (SDET) having proven track record in leading automation and quality teams of enterprise class products for growing organizations.  Presently involved in Automation, DevOps and Performance verticals for enterprise class product’s testing.  Expert in Automation based out of API and UI testing
- Advertisment -

Most Popular

Recent Comments

Translate »