1

I'm aware that I could do this:

var myClass = { /* my class definition */ };
var methodName = 'myMethod';
myClass[methodName](p1,p2,...,pN);

But what should I do if have this:

if(data.someMethodName[0]!== undefined){ ... }

or

data.someMethodName[i].someAttribute

How do I call someMethodName dynamically meaning calling it as a string?

2
  • Exactly the same way. Which is data[someMethodName]() if I understand you correctly. Commented Feb 20, 2013 at 16:03
  • Also that's not a "method call", it's a "property access". Commented Feb 20, 2013 at 16:04

1 Answer 1

2

What you are looking for is the bracket notation:

data[someMethodName][0].

data[ someMethodName[0] ](p1, p2, ...)
Sign up to request clarification or add additional context in comments.

8 Comments

data.someMethodName[i].someAttribute how do I call this?
@Alan: Your example really isn't clear. Please be more specific.
data[someMethodName][0] and data[ someMethodName[0] ] are not the same. are you sure it should be so?
@FelixKling, I showed 2 examples of what I wanted to know about. What was not clear?
@Alan: Whether someMethodName is a string or an array. Whether you want to call a method with the name contained in someMethodName[0] or someMethodName. What someAttribute is. Etc. But apart from that, it's always the same. Whenever you have an invalid identifier name or a variable, you have to use bracket notation instead of dot notation.
|

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.