javascript - 如何检查函数是否已经定义?

标签 javascript jquery

如何检查函数是否已经定义?

最佳答案

检查函数是否存在的 Javascript 函数。

jQuery.isFunction()您可以测试一个参数以检查它是否 (a) 已定义以及 (b) 是否属于“函数”类型。由于您要求使用 jQuery,因此这个函数会让您大开眼界。

jQuery.isFunction(YourFunction)

如果您出于任何原因不想使用 jQuery,这里有一个基于 Idealog 中代码的准系统函数。这将检查变量是否属于 function 类型。

function isFunction(fn){
    return typeof fn === 'function'
}

有时您已经知道它是一个函数并且为了优化而没有理由重新检查它的类型,在这种情况下,这里的函数只是检查是否定义了变量 [可能是一个函数]

function isDefined(foo){
    return typeof(foo) !== 'undefined'
}

如何使用这些功能

使用 jQuery:

function foo(){}
if(jQuery.isFunction(foo)) alert('This is a function');

使用上面提供的任一非 jQuery Javascript 函数。根据使用的上下文,这些函数可能可靠也可能不可靠。查看更多内容

function foo(){}
if(isFunction(foo)) alert('is of type function');
if(isDefined(foo)) alert('if this is a function, it is defined');

检查 undefined 和 using jQuery.isFunction

if (typeof myfunc !== 'undefined' && $.isFunction(myfunc)) {
    //do something
}

Source

jQuery.isFunction() 更好吗?

根据 Kyle Florence jQuery.isFunction() 它在某些情况下可能更胜一筹。在使用 jQuery 方法时在某些边缘情况下特别有用,请参阅他的 explanation .

In certain situations in some browsers, things are incorrectly returned as the "function" type, or things that are in fact functions are returned as another type. There are several test cases you can see here: https://github.com/jquery/jque...

One example:

var obj = document.createElement("object");

// Firefox says this is a function typeof obj; // => "function"

Keep in mind these are mostly edge cases, but the reason $.isFunction was made was simply to be positive about something being a function (which can be quite important for the jQuery library itself, maybe not so much for your code).

谢谢 patrick dw 指出 Kyles 文章。 (Patrick DW 删除了他的帐户)

来自 jQuery.com

Note: As of jQuery 1.3, functions provided by the browser like alert() and DOM element methods like getAttribute() are not guaranteed to be detected as functions in browsers such as Internet Explorer.

关于javascript - 如何检查函数是否已经定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5159652/

相关文章:

javascript - 在 Kendo Grid 中,如何在进行内联编辑时禁用拖动?

javascript - 单击 Chrome 通知时转到已打开的选项卡

PHP 脚本没有被执行

javascript - AJAX HTML 标签不会显示为 HTML 标签,而是在验证时显示为普通文本

javascript - 使用 Pixastic 组合效果/滤镜

javascript - AJAX 与 Rails 3 和 jQuery?

jquery - CSS 背景颜色和文本随 jquery/javascript 变化

javascript - 用javascript转换php的htmlspecialchars()

javascript - 当 Formik 表单更改时更新另一个组件

Javascript:如果冒号则删除最后一个字符