0

I wand to check for the existence of a JavaScript method, when I have a variable with that method name inside it.

Using PHP I could do this:

$method = 'bar';
$object = new Foo;
if(method_exists($object, $method))
{
    //Foo->bar()
}

How can I do this in JavaScript? My first attempt failed:

var method = 'bar';
if(typeof(obj.method) != "undefined")
{
    obj.method();
}
else
{
    obj.default();
}

5 Answers 5

7

Check if the typeof the property is "function", using method as the key into the obj object:

((typeof obj[method] === "function") ? obj[method] : obj.default)();
Sign up to request clarification or add additional context in comments.

2 Comments

+1 Note there are edge cases where typeof variable will say 'function' when it really isn't.
Need to change obj.method to obj[method] (you've got it already for the first use but not the second.
4

I typically just do if(obj.method) {...} but you could always use a try/catch:

try {
    obj.method();
} catch(e) {
    // obj or obj.method didn't exist, so let's try plan b
    obj.planB();
}

2 Comments

+1 for mentioning try/catch as an option which is under-utilized in Javascript.
But this won't work because method is actually a variable that holds the real name of the method.
2
  (obj[method] || obj.default)();

would work too, if you want to one-line it.

Comments

1

['blah'] and .blah are equivalent in a Javascript Object, so you can call your method like

obj[method]();

Where method is a string containing the name of the method to call.

Comments

0

You should the object's method property to be typeof as function. E.g.

 if (typeof(obj[method]) == "function") {
   obj[method]();
 }

Here is a JSFiddle explaining how to check for a function.

1 Comment

This won't work. The problem is method is a variable holding the name of the method. Need to say obj[method] instead of obj.method.

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.