Reputation: 57244
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();
}
Upvotes: 0
Views: 1283
Reputation: 163288
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)();
Upvotes: 7
Reputation: 9096
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.
Upvotes: 0
Reputation: 141877
['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.
Upvotes: 1
Reputation: 2699
(obj[method] || obj.default)();
would work too, if you want to one-line it.
Upvotes: 2
Reputation: 32247
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();
}
Upvotes: 4