8

I have the following code and am wondering how to make the last line work. I addopted a set of api's that current use _view appended as it's namespacing convention and would rather use something like arc.view.$function_name. thx

var arc={};
arc.view={
  say_hello: function(){
    alert("I want to say hello");
  }
}
function say_goodbye(){
  alert("goodbye to you");
}

arc.view.say_hello(); // works
window['say_goodbye'](); // works
// possible to make this work?
window['arc.view.say_hello']();
timpone
  • 19,235
  • 36
  • 121
  • 211

3 Answers3

12
window['arc']['view']['say_hello']();

or

window.arc.view.say_hello()

or

window['arc'].view['say_hello']()

Either the dot syntax or the bracket syntax will work. Dot syntax is really just syntactic sugar for a bracket-based property lookup, so all of the above code snippets are identical. Use bracket syntax when the property name itself is a dynamic value, or when using the property name in dot syntax would cause a syntax error. E.g.:

var dynamicMethodName = someObject.getMethodName();
someOtherObject[dynamicMethodName]();

or

someOtherObject["a key string with spaces and {special characters}"]();
zetlen
  • 3,609
  • 25
  • 22
3

Try this:

jsFiddle

window["arc"]["view"]["say_hello"]();
Gabe
  • 49,577
  • 28
  • 142
  • 181
2

Using the square bracket notation you're actually asking to execute a function in window called arc.view.say_hello, and not a function in the object view (that is a property of the object arc). To be more explicit:

window["arc.view.say_hello"] = function () { alert("hi") };

window["arc.view.say_hello"](); // "hi"

If you want to call a function in the way you described, you have to "resolve" the objects chain. You can create an utility function for that. Something like:

var arc={};
arc.view={
  say_hello: function(){
    alert("I want to say hello");
  }
}
function say_goodbye(){
  alert("goodbye to you");
}

function call(id) {
    var objects = id.split(".");
    var obj = this;

    for (var i = 0, len = objects.length; i < len && obj; i++)
        obj = obj[objects[i]];

    if (typeof obj === "function")
        obj();
}

call("say_goodbye");
call("arc.view.say_hello");

You could also extend the utility function to use arguments (or you could just return the reference to the function).

ZER0
  • 24,846
  • 5
  • 51
  • 54