Bin Chen
Bin Chen

Reputation: 63309

javascript: how to judge a function name exists?

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

Upvotes: 1

Views: 1809

Answers (3)

Nick Craver
Nick Craver

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

Dr.Molle
Dr.Molle

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

jAndy
jAndy

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

Related Questions