Alan Coromano
Alan Coromano

Reputation: 26008

Dynamic method call in javascript

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?

Upvotes: 1

Views: 77

Answers (1)

marekful
marekful

Reputation: 15351

What you are looking for is the bracket notation:

data[someMethodName][0].

data[ someMethodName[0] ](p1, p2, ...)

Upvotes: 2

Related Questions