...

View Full Version : Calling a js function when name is stored in a variable



NancyJ
06-17-2008, 05:22 PM
I have a function name stored in a variable - how do I call the function?

Philip M
06-17-2008, 05:35 PM
Try:-

var test = "functionName";
eval(test + '()');

Trinithis
06-17-2008, 06:32 PM
objectToCallWith[string](params);
If the function is a global function, use window.



function succ(x) {
return x + 1;
}

var str = "succ";

var a = succ(1);
var b = window["succ"](2);
var c = window[str](3);

var f = window["succ"];
var d = f(4);

liorean
06-17-2008, 06:32 PM
Is it a global function? If so, then you can do window[name]();. If it's a local function, you need to use eval(name)(); or eval(name+'()'); like Philip M suggests.

NancyJ
06-17-2008, 06:41 PM
um... whats the difference between a local and global function?

Trinithis
06-17-2008, 06:42 PM
Edit: A local function is a function defined within another function.

I have no idea if this is a bad idea or not (I just thought of it), but for local functions, you can avoid eval for them if you attach them to a variable that denotes the local scope:



function f() {
var g = function() {
alert("g");
};
var local = {
g: g
};
var str = "g";
local[str]();
}
f();

NancyJ
06-17-2008, 08:25 PM
huh. Didn't know you could define functions within functions. I guess mine would be a global function then heh.

abduraooft
06-18-2008, 10:27 AM
I have a function name stored in a variable - how do I call the function? Subscribed and saved this thread for reference :)
Good question and many thanks :thumbsup:

Philip M
06-18-2008, 12:26 PM
Thanks all round - except for the guy who provide the answer! :p:p



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum