Javascript 如何检查函数是否存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30215901/
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
How to check if function exist?
提问by Haroldas
How to check if is function on jquery, but function is in another .js file?
如何检查 jquery 上是否有函数,但函数在另一个 .js 文件中?
validation.js:
验证.js:
if ($.isFunction('payment')) {
$('[data-numeric]').payment('restrictNumeric');
$('.cc-number').payment('formatCardNumber');
$('.cc-exp').payment('formatCardExpiry');
$('.cc-cvc').payment('formatCardCVC');
}
this is false because func payments is in the payments.js .
这是错误的,因为 func 付款在 Payments.js 中。
回答by Anik Islam Abhi
Try like this
像这样尝试
if (typeof payment === "function")
{
// Do something
}
回答by Haroldas
problem is solved. its works:
问题解决了。其作品:
if ($.fn.payment) {
//do something
}
回答by Shijin TR
Try to check like as follows,
尝试检查如下,
if (typeof payment !== 'undefined' && $.isFunction(payment)) {
$('[data-numeric]').payment('restrictNumeric');
$('.cc-number').payment('formatCardNumber');
$('.cc-exp').payment('formatCardExpiry');
$('.cc-cvc').payment('formatCardCVC');
}
回答by VVV
You can check if a function exists using window
您可以使用以下方法检查函数是否存在 window
For example
例如
var fn = window['NameOfTheFunction'];
if(typeof fn === 'function') {
doSomething();
}
If your function in payment.js is part of a self contained function, you need to set it to so the window object can "see" it by adding this in your self contained function:
如果您在 payment.js 中的函数是自包含函数的一部分,则需要将其设置为,以便窗口对象可以通过在自包含函数中添加以下内容来“看到”它:
window.NameOfTheFunction = NameOfTheFunction;

