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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20027715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:55:03  来源:igfitidea点击:

jQuery isFunction check error "function is not defined"

jqueryfunction

提问by user1995781

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/

回答by jcsanyi

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 myfuncis 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 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/

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

回答by user2249160

try this

尝试这个

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