Javascript calling a function on a window object

I have the following code and I am wondering how to do the last job. I added an api suite that uses the current use of _view, added as a naming 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'](); 
+6
source share
3 answers
 window['arc']['view']['say_hello'](); 

or

 window.arc.view.say_hello() 

or

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

Either point syntax or parenthesis syntax will work. The Dot syntax is really just syntactic sugar for finding properties based on parentheses, so all of the above code snippets are identical. Use binding syntax when the property name itself is a dynamic value, or when using the property name in point syntax will result in a syntax error. For instance:.

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

or

 someOtherObject["a key string with spaces and {special characters}"](); 
+10
source

Try :

jsFiddle

 window["arc"]["view"]["say_hello"](); 
+3
source

Using quadratic notation, you are actually asking to execute a function in a window called arc.view.say_hello , not a function in a view object (this is a property of the arc object). To be more explicit:

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

If you want to call the function as you described, you need to "enable" the chain of objects. You can create a utility function for this purpose. Sort of:

 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 can also extend the utility function to use arguments (or you can simply return a link to the function).

+2
source

Source: https://habr.com/ru/post/913214/


All Articles