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:

Scenario:


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.

Example:


Shapes: Triangle, Square

Property: Color, Label

Pseudo Code:


Triangle
{
function setColor(arg1) {  },

function setLabel(arg1) {  }
}

Square
{
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
objShape[methodName](arg1);


Hope this will be useful !!!

mm
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
RELATED ARTICLES
- Advertisment -

Most Popular

Recent Comments

Translate »