PDA

View Full Version : javascript question



tc101
March 17th, 2009, 06:06 PM
Suppose I have a function like this which calls a second function:

function Fun_1()
{
Fun_2();
}

How can I code this so I can pass the name of the second function

Fun_1(“Fun_2”)

function Fun_1(Fname)
{
How do I call Fname here?
}

Tibuda
March 17th, 2009, 06:08 PM
You can define functions as variables.


var fun2 = function() {
// Whatever
}

function fun1(f) {
f();
}

fun1(fun2);

tenmilez
March 17th, 2009, 08:15 PM
You could use the eval function.

not tested



f1("f_2");

function f1(f2) {
eval(f2 + "()");
}

function f_2() {
// stuff
}

simeon87
March 17th, 2009, 11:19 PM
You could use the eval function.

Eval shouldn't be used when it's not needed.

soltanis
March 18th, 2009, 02:09 AM
Store the function as a variable and pass the variable to the function, like in the first response.

tc101
March 18th, 2009, 03:16 AM
Thanks !

Reiger
March 18th, 2009, 05:31 AM
You can tweak the store-as-a-variable behaviour a little:


function f1 () {
}

function f2 (funct) {
}

var fvar = f1;
f2(fvar);