Reputation: 63309
Is it possible to judge if a function names exists before calling it?
Upvotes: 1
Views: 1809
Reputation: 630389
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
.
Upvotes: 4
Reputation: 117334
If you only want to avoid errors, you can turn the tables:
try{function2call();}
catch(e){alert('function2call() doesn\'t exist');}
Upvotes: 0
Reputation: 236012
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.
Upvotes: 1