Forum Moderators: open

Message Too Old, No Replies

Use typeof with string to determine if function exists?

         

JAB Creations

7:37 am on Aug 17, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm trying to determine if a function exists however I want to do so dynamically (passing it as a string to a function).

The problem is that inside of the function if I alert the typeof it obviously tells me that the string is a string so how do I have JavaScript tell me if a function exists by using the string containing the function's name? I've tried a few things such as using eval and variable variables without success.

I don't use frameworks as I code JavaScript using actual JavaScript however researching this brought up endless framework results on search engines hence why I'm posting this question.

Thoughts please?

- John

JAB Creations

7:48 am on Aug 17, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Because I made the post meant that I'd naturally find it five minutes later.

- John

if (eval("typeof " + function_name_here + " == 'function'")) {alert('defined!');} else {alert('not defined');}

JAB Creations

8:01 am on Aug 17, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Because I'm super-awesome I'm going to post a related example that executes the function if it exists...

- John

if (typeof function_name_here=='string' && eval('typeof ' + function_name_here)=='function') {eval(function_name_here+'()');}

astupidname

9:12 am on Aug 17, 2010 (gmt 0)

10+ Year Member



No need for the eval's really, as it appears you are looking for globally available function's which are properties of the window object. Say you are looking for function named 'foo', you can do:
if (typeof window['foo'] == 'function') {
foo();
}
Or of course you could try/catch it:
try{
foo();
} catch(er) {
alert('foo not available');
}

JAB Creations

10:34 am on Aug 17, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks ASN, that worked beautifully and is much more elegant! There sure are a lot of nooks and crannies when it comes to JavaScript. :)

- John

var z = 'function_name_in_string';
alert(typeof window[z]);