Trax Trax - 1 month ago 11
Javascript Question

Dynamically invoke object

I have an object :

const Foo = {
bar: function(baz) { ... }
}


I want to do something like:

let x = 'Foo';
let y = 'cookies';

x.bar(y);


I tried using eval:
eval(x + '.bar' + '(' + y + ')');
but it's not working.

I cannot use window, this is code will not run in a browser. Any suggestions are welcomed.

Answer Source

const Foo = {
  bar: function(baz) { 
    console.log(baz);
  }
}

let x = 'Foo';
let y = 'cookies';

eval(x).bar(y);