2

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?

0

3 Answers 3

2
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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.