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 = {}; = {}; = {}; = 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 = [];

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

} //

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

// we should be able to see the search history in the
// namespace now

And there you have it. Namespaces in JavaScript.


  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.

  2. This one us very useful and helpful for us. It look you spend a lot of time or effort to make this one. Keep it up. Now it's time to avail Baby Liquid Soap for more information.