How to check if a JS function is defined?

L

laredotornado

Hello,

What is a cross-browser way to check if a function has been defined?

It seems that this code

if (myFn) {
myFn();
}

executes whether myFn is defined or not. When it is not, a JS error
results.

Your help is greatly appreciated, - Dave
 
I

Ivo

What is a cross-browser way to check if a function has been defined?
It seems that this code

if (myFn) {
myFn();
}

executes whether myFn is defined or not. When it is not, a JS error
results.

I don't see how that seems, but have you tried this if statement:
if ( typeof myFn==='function' )
 
R

RobG

Hello,

What is a cross-browser way to check if a function has been defined?

It seems that this code

if (myFn) {
myFn();
}

executes whether myFn is defined or not. When it is not, a JS error
results.

Use typeof:

function someFn(){}

function isFn(funcRef)
{
return 'function' == typeof funcRef;
}

alert('Is someFn a function? ' + isFn(someFn) );
 
T

Thomas 'PointedEars' Lahn

RobG said:
What is a cross-browser way to check if a function has been defined?
[...]

Use typeof:

function someFn(){}

function isFn(funcRef)
{
return 'function' == typeof funcRef;
}

alert('Is someFn a function? ' + isFn(someFn) );

Note that for host object's methods the `typeof' operation may evaluate to
"object" as well.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top