Storing function name in a variable and invoke that function in javascript


Problem: How to store a function name in a javascript variable and invoke that particular function. This post can be classified as a quick tip,

as these kind of scenarios are on need basis

Solution:

Inside JSP:

// Create a javascript array that holds the function names. Our goal is to to use the variables stored in the array and convert them to call a

// function same as  the name stored in the variable

<head>

var myArray = new Array(2);

myArray[0] = “onefunction”;

myArray[1]=”anotherfunction”;

</head>

<body onload=”demonstrate(myArray);”

Inside Javascript (.js) file

//Declare a global variable to hold function names

var fnnames;

function demonstrate(functionnames){

var myfn= functionnames;

for(var i =0; i < myfn.length; i++){

eval(myfn[i] + “Hello”); //calling function1 with a parameter “Hello1”, Similarly Calling function2 as well

}

}

//The below functions get called

function onefunction(String param){

alert(Param);

}

function anotherfunction(String param){

alert(Param);

}

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: