How to create static functions with namespace in javascript?

Now I am using this method:

window.Foo = { alpha: function() {}, bravo: function(arg) {} } window.Bar = { charlie: function(arg) {} } Foo.alpha() Bar.charlie() 

But I suspect that this is not the โ€œrightโ€ way to do something because (1) my IDE is suffocating in understanding what I mean in several ways (for example, it will not autocomplete function names if I type Foo. ) and (2) if I typeof eachone over namespaces and return typeof eachone , I get String .

+4
source share
3 answers

This code:

 for(var key in window.Foo) { // Code } 

assigns the property name to the variable key , which is a string. If you need a related object (or function), use this instead:

 for(var key in window.Foo) { var obj = window.Foo[key]; // Code using obj } 

As Matthew Flaschen said dynamic languages โ€‹โ€‹such as JavaScript are hard to parse, so if your ID environment doesnโ€™t understand something, donโ€™t worry too much about it.

+4
source

This is perfectly normal if you do not need private variables. Dynamic languages โ€‹โ€‹are hard to parse, and your IDE just doesn't get it.

An alternative, especially if you need a private class field, is:

 window.Foo = new (function(){ var some_private; this.alpha = function(){}, this.bravo = function(arg){// use arg and some_private} })(); 

Regarding the iteration, I suspect you are using something like:

 for(var key in window.Foo) { print(typeof key); } 

Try:

 for(var key in window.Foo) { print(typeof window.Foo[key]); } 
+3
source

Try it. Maybe your IDE will handle this correctly

 var Foo = { test: function() {}, test2: function() {} }; for(var prop in Foo) { console.log(typeof Foo[prop]); // Will log 'function' } window.Foo = Foo; 
+2
source

All Articles