View Full Version : Check for the existence of a function

09-14-2004, 09:11 PM
How do you check for the existence of a function. I know how to do it for a variable, but never tried for a function until now.

I call a function on a page, if its not there, do nothing.

Has any written code like this before? Can it be done in javascript? (I've googled for the last couple of hours without finding a solution.)

I accidently posted here and couldn't delete it, if you're an mod or admin, please delete my post:

09-14-2004, 09:42 PM
Oh, BTW, hoping for a solution that does not use a try catch:

try {
} catch(er) {
//do nothin

09-14-2004, 09:44 PM
if(typeof functionname=='function')
/* dostuff */;

09-14-2004, 10:11 PM
liorean, your code works great

if(typeof functionname== 'function')

However, my function has parens, () in it.

if(typeof functionname() == 'function')

I still get a "object expected" in IE and a "functionname is not defined" in firebird.

I may be forced to use a try catch.

09-14-2004, 10:22 PM
No, no, no. Do just as I said enter only the function name, not the parentheses. You don't want to call the function (that's what you use the parentheses for), only detect if it exists.
if(typeof functionname=='function')

09-14-2004, 11:19 PM
Sweet. That did the trick. I did see instructions on how to check for String, object, etc. for typeOf. I'll have to find it again to see if it mentioned the detection of functions correctly.

Thanks again.