Javascript 调用前检查函数是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13657204/
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-24 12:36:13  来源:igfitidea点击:

Check if Function Exists before Calling?

javascriptjquery

提问by Amjad Ali

Possible Duplicate:
jQuery test for whether an object has a method?

可能的重复:
jQuery 测试对象是否有方法?

I want to set if Function Exists before Calling javascript can you help me how do this and apply on this script

我想在调用 javascript 之前设置函数是否存在,你能帮我如何做到这一点并应用到这个脚本上

$(document).ready(function() {
   $(".cs-text-cut").lettering('words');
});

回答by gregwhitworth

I'm assuming that you're wanting to check and make sure that letteringexists, try this:

我假设你想检查并确保它lettering存在,试试这个:

http://api.jquery.com/jQuery.isFunction/

http://api.jquery.com/jQuery.isFunction/

Here's an example:

下面是一个例子:

if ( $.isFunction($.fn.lettering) ) {
    $(".cs-text-cut").lettering('words');
}

回答by harikrishnan.n0077

Use this to check if function exists.

使用它来检查函数是否存在。

<script>
if ( typeof function_name == 'function' ) { 
        //function_name is a function
}
else
{
 //do not exist
}
</script>

回答by jfriend00

If it's the letteringfunction you want to test for, you can do so like this;

如果是lettering你要测试的功能,你可以这样做;

$(document).ready(function() {
    var items = $(".cs-text-cut");
    if (items.lettering) {
        items.lettering('words');
    }
});

Or, if you want to make absolutely sure items.letteringis a function before attempting to call it, you can do this:

或者,如果您想items.lettering在尝试调用之前绝对确定是一个函数,您可以这样做:

$(document).ready(function() {
    var items = $(".cs-text-cut");
    if (typeof items.lettering === "function") {
        items.lettering('words');
    }
});

Or, if you really don't control the environment so you don't really know if the lettering function call is going to work or not and might even throw an exception, you can just put an exception handler around it:

或者,如果你真的不控制环境,所以你真的不知道刻字函数调用是否会工作,甚至可能抛出异常,你可以在它周围放置一个异常处理程序:

$(document).ready(function() {
    try {
        $(".cs-text-cut").lettering('words');
    } catch(e) {
        // handle an exception here if lettering doesn't exist or throws an exception
    }
});

回答by inhan

typeof $({}).lettering == 'function'or $.isFunction($({}).lettering)should return a boolean for whether it's available yet or not.

typeof $({}).lettering == 'function'或者$.isFunction($({}).lettering)应该返回一个布尔值是否可用。