Friday, March 16, 2012

javascript namespaces

Well, I lied already: JavaScript doesn't really have namespaces — at least not exactly. But, we can fake it quite easily using objects, which readily serve the same purposes:

var com = {};
com.google = {};
com.google.www = {};
com.google.www.search = function(s) {

  // since we're actually working in the context of an object,
  // we can refer to "this" to set static-ish variables, like a search history:
  if (!this.search_history) {
    this.search_history = [];
  }
  this.search_history.push(s);

  // perform the actual "search" ...
  alert("No results for " + s + "! Try searching with svidgen.com instead!");

} // com.google.www.search()


// you can then use "with"
// even though you shouldn't generally be using "with" ...
with (com.google.www) {
  search("for something");
  search("for something else");
}

// we should be able to see the search history in the
// namespace now
alert(com.google.www.search_history.length);

And there you have it. Namespaces in JavaScript.

2 comments: