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 wou
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}"]();
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).
Try this:
jsFiddle
window["arc"]["view"]["say_hello"]();