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?

5
  • 1
    Because you can reference nested properties like that. And I know chrome will not work referencing it like that. Commented Nov 15, 2016 at 20:07
  • make sure whatever function youre calling is actually in the window scope. if you used a window.onload or a $(function(){...}) then it's not in the window scope. Commented Nov 15, 2016 at 20:10
  • @Misaz - of course it is. if it's not in the window scope then accessing it through the window will not work. Commented Nov 15, 2016 at 20:13
  • @Iwrestledabearonce. window["console.log"]("blah"); does not work in chrome... unless someone did window["console.log"] = console.log.bind(console); Commented Nov 15, 2016 at 20:14
  • @epascarello - that's why i deleted the comment. its the dot notation that breaks it, not the bracket notation. i get what youre saying. Commented Nov 15, 2016 at 20:16

2 Answers 2

1

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

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

See this entry for further details.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.