admin管理员组文章数量:1323737
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();
}
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();
}
Share
Improve this question
asked Aug 10, 2011 at 0:07
XeoncrossXeoncross
57.3k83 gold badges271 silver badges371 bronze badges
5 Answers
Reset to default 7Check 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. E.g.
if (typeof(obj[method]) == "function") {
obj[method]();
}
Here is a JSFiddle explaining how to check for a function.
本文标签: Variable methods in Javascript objectsStack Overflow
版权声明:本文标题:Variable methods in Javascript objects - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742119120a2421612.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论