4

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 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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]); 
}

1 Comment

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.
2

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.