jQuery isFunction检查错误“函数未定义”

时间:2022-07-29 20:23:05

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

myfunc未定义

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

我该如何进行检测?这是我的工作测试:http://jsfiddle.net/3m3Y3/

2 个解决方案

#1


117  

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.

但是 - 如果myfunc不是一个函数而且不是任何其他定义的变量,那么它仍然会返回一个错误,尽管它是一个不同的错误。像myfunc这样的东西没有定义。

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/

这里的工作示例:http://jsfiddle.net/sXV6w/

#2


11  

try this

尝试这个

if(typeof myfunc == 'function'){
    alert("exist");
}else{
    alert("not exist");
}

#1


117  

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.

但是 - 如果myfunc不是一个函数而且不是任何其他定义的变量,那么它仍然会返回一个错误,尽管它是一个不同的错误。像myfunc这样的东西没有定义。

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/

这里的工作示例:http://jsfiddle.net/sXV6w/

#2


11  

try this

尝试这个

if(typeof myfunc == 'function'){
    alert("exist");
}else{
    alert("not exist");
}