Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery isFunction check error "function is not defined"

I want to do a check whether a function exist or not before trying to run it. Here is my code:

if ($.isFunction(myfunc())) {     console.log("function exist, run it!!!"); } 

However, when the function is not available I got the error:

myfunc is not defined

How can I do the detection? Here is my working test: http://jsfiddle.net/3m3Y3/

like image 341
user1995781 Avatar asked Nov 17 '13 05:11

user1995781


People also ask

How do you check function is defined or not in jQuery?

With jQuery. isFunction() you may test a parameter to check if it is (a) defined and (b) is of type "function." Since you asked for jQuery, this function will tickle your fancy.

How do you know if a function is undefined?

Use the typeof operator to check if a function is defined, e.g. typeof myFunction === 'function' . The typeof operator returns a string that indicates the type of a value. If the function is not defined, the typeof operator returns "undefined" and doesn't throw an error.

How do you check if a function exists or not?

Alternatively, we can use the typeof operator. This operator will check whether the name of the declared function exists and whether it is a function and not some other type of object or primitive.

How do you check if a method exists on an object JavaScript?

Use the typeof operator to check if a method exists in a class, e.g. if (typeof myInstance. myMethod === 'function') {} . The typeof operator returns a string that indicates the type of the specific value and will return function if the method exists in the class.


1 Answers

By putting () after the function name, you're actually trying to run it right there in your first line.

Instead, you should just use the function name without running it:

if ($.isFunction(myfunc)) { 

However - If myfunc is not a function and is not any other defined variable, this will still return an error, although a different one. Something like myfunc is not defined.

You should check that the name exists, and then check that it's a function, like this:

if (typeof myfunc !== 'undefined' && $.isFunction(myfunc)) { 

Working example here: http://jsfiddle.net/sXV6w/

like image 111
jcsanyi Avatar answered Oct 23 '22 10:10

jcsanyi