Is it possible to judge if a function names exists before calling it?
3 Answers
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.
4 Comments
.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 :)this["functionName")() would probably crash like disastrous if it's not a function object.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.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
If you only want to avoid errors, you can turn the tables:
try{function2call();}
catch(e){alert('function2call() doesn\'t exist');}
2 Comments
try/catch blocks have real performance issues, not to mention throwing an exception is way more expensive than the if checks for type.alert('alert is a function:'+(typeof alert=='function')); in MSIE, will this return the expected?
if(name_of_funcion){/*what to do then*/}