0

I have some code where I need to call a function when I have it's name in a string. For example:

var util = {
    exByName: function(name) {
        window[name](arguments);
    }
};
util.exByName("console.log", "blah");

When I run this, the error 'Uncaught TypeError: window[name] is not a function' however, when I ran this in the browser (Opera):

window["console.log"]("blah");

It works fine. Can someone help me with this?

gus27
  • 2,616
  • 1
  • 21
  • 25

2 Answers2

1

With other browsers and namespaced functions like console.log you have to use:

window["console"]["log"]("blah")

See this entry for further details.

Community
  • 1
  • 1
gus27
  • 2,616
  • 1
  • 21
  • 25
1

You cannot access nested object properties using the dot notation in brackets.

Instead, access different nested levels via separate brackets:

window["console"]["log"]("foo");

More about object property accessors on MDN.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94