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 !!!

From Around The Web

From the web