JavaScript namespaces

Based on the 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 using namespacing.

3 Responses to “JavaScript namespaces”

  1. Nicely done.

  2. 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. :-)

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

Leave a Reply
Not required

CODE: Please escape code and wrap in <pre><code>, doing so will automatically syntax highlight