jQuery isFunction check error “function is not defined”

后端 未结 2 436
孤街浪徒
孤街浪徒 2021-01-31 14:09

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, ru         


        
相关标签:
2条回答
  • 2021-01-31 14:47

    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/

    0 讨论(0)
  • 2021-01-31 15:00

    try this

    if(typeof myfunc == 'function'){
        alert("exist");
    }else{
        alert("not exist");
    }
    
    0 讨论(0)
提交回复
热议问题