Based on the [Prototype](http://prototypejs.org) [namespacing made easy](http://thinkweb2.com/projects/prototype/namespacing-made-easy/), except this doesn’t require Prototype.

 String.prototype.namespace = function(separator) {
  var ns = this.split(separator || '.'), p = window, i;
  for (i = 0; i < ns.length; i++) {
    p = p[ns[i]] = p[ns[i]] || {};
  }
};

[I’ve published 38 videos for new developers, designers, UX, UI, product owners and anyone who needs to conquer the command line today.](https://training.leftlogic.com/buy/terminal/cli2?coupon=BLOG\&utm_source=blog\&utm_medium=banner\&utm_campaign=remysharp-discount)

Published 4-Feb 2008 under #code & #javascript & #namespace. [Edit this post](https://github.com/remy/remysharp.com/blob/main/public/blog/javascript-namespaces.md)

Comments

Lock Thread

Login

Add Comment[M ↓   Markdown]()

[Upvotes]()[Newest]()[Oldest]()

?

Anonymous

0 points

15 years ago

@Mark - how on earth did I miss that! Corrected now - cheers.

?

Anonymous

0 points

15 years ago

The "i=0" in the for loop should be declared as "var i=0", otherwise "i" becomes set at the global level - exactly what namespaces should be preventing. :-)

![](<https://download.remysharp.com/comments/avatars/Paul Irish.jpg>)

Paul Irish

0 points

16 years ago

Nicely done.

[Commento](https://commento.io)