English 中文(简体)
Java印物体的可变方法
原标题:Variable methods in Javascript objects

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

使用购买力平价 我可以这样做:

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

我如何在 Java山这样做? 我的第一次尝试失败了:

var method =  bar ;
if(typeof(obj.method) != "undefined")
{
    obj.method();
}
else
{
    obj.default();
}
最佳回答

<>代码> 财产为<代码>功能”,使用<代码>method 缩略语 反对:

((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)();

如果你想要一条一条线的话,也会奏效。

[ 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.





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签