简体   繁体   English

如何在JavaScript中检查功能是否存在

[英]How to check if function is exist or not in javascript

I want to check if the class has a method or not in javascript. 我想检查该类是否在javascript中具有方法。 Suppose for checking normal function I can use like - 假设要检查正常功能,我可以使用-
Using Jquery: 使用jQuery:

function foo(){}
if($.isFunction(foo)) alert('exists');

Or from normal javascript: 或从普通的javascript:

function foo(){}
if(typeof foo != 'undefined') alert('exists');

But I want to check for a member function like if I have a class and method like- 但是我想检查一个成员函数,例如我是否有一个类和方法,例如-

function ClassName(){
 //Some code
}

ClassName.prototype.foo = function(){};

And I have a method name stored in a variable, and I am calling the method using this variable like- 我有一个存储在变量中的方法名称,我正在使用此变量调用该方法,例如-

var call_it = 'foo';
new ClassName()[call_it]();

But for the handling runtime error, I want to check the method exist or not before calling. 但是对于处理运行时错误,我想在调用之前检查该方法是否存在。 How can I do that? 我怎样才能做到这一点?

if (ClassName.prototype[call_it]) {
    new ClassName()[call_it]();
}
var call_it = 'foo';
if (typeof ClassName.prototype[call_it] === "function"){
   new ClassName()[call_it]();
}

OR 要么

 var call_it = 'foo';
 var instance = new ClassName();
 if (typeof instance[call_it] === "function"){
     instance[call_it]();
 }

You should use typeof to ensure the property exists and is a function 您应该使用typeof来确保该属性存在并且是一个函数

if ( typeof yourClass.foo == 'function' ) { 
    yourClass.foo(); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM