tags:

views:

64

answers:

3

Right now, I'm using this fashion:

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

Foo.alpha()
Bar.charlie()

But I suspect that this is not the "correct" way to do things since (1) my IDE chokes up in understanding what I mean in several ways (e.g., won't autocomplete function names if I type in Foo.) and (2) if I iterate through the namespaces, and just return typeof eachone, I get String.

+3  A: 

That's completely fine if you don't need private variables. Dynamic languages are hard to parse, and your IDE just isn't getting this.

An alternative, especially if you do 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}
})();

As for the iteration, I suspect you're using something like:

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

Try:

for(var key in window.Foo) 
{ 
  print(typeof window.Foo[key]); 
}
Matthew Flaschen
Note that `for each ... in` is a Mozilla-only construct. Also `for (key in window.Foo)` might cause `key` to be declared as a property on the global object (and in ES5 under Strict Mode will cause a `ReferenceError`), `for (var key in window.Foo)` is recommended instead.
CMS
Thank you, @CMS.
Matthew Flaschen
+2  A: 

Try this one. Maybe your IDE will deal with it properly

var Foo = {
   test: function() {},
   test2: function() {}
};

for(var prop in Foo) {
    console.log(typeof Foo[prop]); // Will log 'function'
}

window.Foo = Foo;
fantactuka
+3  A: 

This code:

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

only assigns the name of the property to the variable key, which is a string. If you need the associated 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 IDE doesn't understand something, don't worry too much about it.

Na7coldwater