0

There is like 5 questions already answered but all of them says only how to create, what I need is to access. In PHP we have:

$foo = new Foo();
$bar = 'methodName';
$foo->{$bar}();

How can I do this in JavaScript without using plugins? Code below fires method 'bar' of object 'foo', but I need to fire method from 'foo' object which name is assigned to variable 'bar'.

var foo = new Foo(),
    bar = 'methodName';
foo.bar();
grinry
  • 421
  • 1
  • 7
  • 17
  • 2
    `foo[bar]()` should do it. This has been asked too many times to count: http://stackoverflow.com/questions/5187530/variable-variables-in-javascript – danronmoon Nov 11 '15 at 20:15

1 Answers1

2

Try this: foo[bar]();

This looks up the member name held in var bar on object foo, and invokes it as a method.

emackey
  • 11,818
  • 2
  • 38
  • 58