Forum Moderators: open

Message Too Old, No Replies

Calling a function whose name is stored in a string

Is this possible to achieve? If so, how?

         

dnimrodx

12:17 am on Feb 16, 2004 (gmt 0)

10+ Year Member



Hello,

I have stepped into a bit of a problem. I need a determined javascript function to call another user-defined js function depending on a different number of reasons.

The problem: the function name is passed as a parameter in the form of a string. It is stored in an object (kind of a class type of, with multiple members and nodes as well) for later use (and is also appended to an HTML tag event handler dinamically after the page is loaded).

The question: since there is no (real) pointer capabilities in javascript, how can I call the function, whose name is stored as a string?

Please note the function name must reside as a string in the object mentioned above (cannot use the object pointer).

As always, all help is welcome. Thank you. :)

d#Nimrod

Purple Martin

12:31 am on Feb 16, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



eval is your friend! It evaluates the contents of a string and executes it as if it were normal code. You can build complex stuff by concatenating strings with the plus sign. The following code is a quick demo.


function callPerson(arg) {
alert(arg);
}
var myString1 = "callPerson";
var myString2 = "Bob";
eval( myString1 + "(" + myString2 + ")" );

dnimrodx

12:57 am on Feb 16, 2004 (gmt 0)

10+ Year Member



Thanks a lot Purple Martin. I have heard of eval before but, to be honest, never paied attention to it.

I had absolutely no idea it could be used in that way -- many thanks for the valuable tip!