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:

  1. You blog provides a workaround for creating namespaces in JavaScript using objects. While JavaScript doesn't have native support for namespaces, the example demonstrates how objects can be utilized to mimic namespace-like behavior. By nesting objects, you can organize your code and create a hierarchical structure similar to namespaces.
    To know more about in detail then Java Certification Course in Lucknow would be better option.

    ReplyDelete