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();
}
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)();
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();
}
(obj[method] || obj.default)();
would work too, if you want to one-line it.
['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.
You should the object's method property to be typeof as function . Eg
if (typeof(obj[method]) == "function") {
obj[method]();
}
Here is a JSFiddle explaining how to check for a function.
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.