1

Is it possible to judge if a function names exists before calling it?

1
  • 2
    tried this? if(name_of_funcion){/*what to do then*/} Commented Nov 30, 2010 at 12:00

3 Answers 3

4

You an check typeof for the function, for example:

if(typeof this["functionName"] != "undefined") {
  alert("uh oh, doesn't exist");
}

If you need to check if it exists and is a function to be extra sure:

if(typeof this["functionName"] == "function") {
  this["functionName"](); //it exists, call it
}

Or the more relaxed version:

if(this["functionName"]) this["functionName"]();

If the name doesn't change (e.g. I misinterpreted the question) just use dot notation, like this:

if(this.functionName) this.functionName();

Or course it doesn't have to be this...whatever object you're checking on, use that, if it's a global function use window.

Sign up to request clarification or add additional context in comments.

4 Comments

what if 'functionName' is not a function?
@jAndy - He's wanting a function to call that may or may not be defined... you could reverse it of course and check the .toString() or typeof for function, but I'd say you have bad naming overlap in those cases...often you want both, for example it may be a function or a selector, or a bool, there are several examples of this across frameworks :)
I don't know.. this["functionName")() would probably crash like disastrous if it's not a function object.
@jAndy - It totally depends on the context as to what you want here, for example your in check would also be the same level of type specificity here...it depends how specific you want to be, I'll update to provide the option none the less.
1

depends pretty much on the scope you're in.

But in general if( 'function_name_to_check' in this) would return true if there is a property in the global or local scope which has that name.

This check must be followed by an additional check for the type:

if( typeof this.function_name_to_check === 'function') { }

to be sure that this IS a function.

Comments

0

If you only want to avoid errors, you can turn the tables:

try{function2call();}
catch(e){alert('function2call() doesn\'t exist');}

2 Comments

This is a bad idea in all cases, try/catch blocks have real performance issues, not to mention throwing an exception is way more expensive than the if checks for type.
So what do you mean why exists there a construct like try/catch, if it's bad in all cases? Try alert('alert is a function:'+(typeof alert=='function')); in MSIE, will this return the expected?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.