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

JS_Dynamic_Method_Calling

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.

https://secure.payza.com/?9Eof021p%2fzsiF22jI3Jrvxjjwi4KPSPlvQBju%2bGEKNs%3d

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

From Around The Web

From the web

loading...