简体   繁体   中英

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. Suppose for checking normal function I can use like -
Using Jquery:

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

Or from normal 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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