ritesh
ritesh

Reputation: 2265

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?

Upvotes: 2

Views: 1040

Answers (3)

Khanh TO
Khanh TO

Reputation: 48972

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

Upvotes: 2

Osama Jetawe
Osama Jetawe

Reputation: 2705

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

Upvotes: 0

Barmar
Barmar

Reputation: 780974

if (ClassName.prototype[call_it]) {
    new ClassName()[call_it]();
}

Upvotes: 2

Related Questions