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?
asked Feb 20, 2013 at 16:01
Alan Coromano
26.2k55 gold badges141 silver badges218 bronze badges
1 Answer 1
What you are looking for is the bracket notation:
data[someMethodName][0].
data[ someMethodName[0] ](p1, p2, ...)
answered Feb 20, 2013 at 16:03
marekful
15.4k6 gold badges39 silver badges63 bronze badges
Sign up to request clarification or add additional context in comments.
8 Comments
Alan Coromano
data.someMethodName[i].someAttribute how do I call this?Felix Kling
@Alan: Your example really isn't clear. Please be more specific.
Alan Coromano
data[someMethodName][0] and data[ someMethodName[0] ] are not the same. are you sure it should be so?Alan Coromano
@FelixKling, I showed 2 examples of what I wanted to know about. What was not clear?
Felix Kling
@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. |
lang-js
data[someMethodName]()if I understand you correctly.