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]] || {};
}
};
This isn’t so much to ditch Prototype, but to [encourage](http://yuiblog.com/blog/2007/06/12/module-pattern/) [using](http://snook.ca/archives/javascript/javascript_name/) [namespacing](http://www.dustindiaz.com/namespace-your-javascript/).
[](https://training.leftlogic.com/buy/terminal/cli2?coupon=BLOG\&utm_source=blog\&utm_medium=banner\&utm_campaign=remysharp-discount)
[READER DISCOUNTSave $50 on terminal.training](https://training.leftlogic.com/buy/terminal/cli2?coupon=BLOG\&utm_source=blog\&utm_medium=banner\&utm_campaign=remysharp-discount)
[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)
[$49 - only from this link](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. :-)

Paul Irish
0 points
16 years ago
Nicely done.
[Commento](https://commento.io)