Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create namespaced static functions in Javascript?

Tags:

javascript

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.

like image 770
Steven Avatar asked Jan 21 '23 14:01

Steven


1 Answers

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.

like image 158
Na7coldwater Avatar answered Feb 05 '23 10:02

Na7coldwater