Monday, February 4th, 2008

Namespaced made easy with Prototype

Category: JavaScript, Prototype

kangax keeps up his “Prototype by example”-ness by showing a use of Enumerable#inject.

He shows us namespacing made easy:

javascript

  1. String.prototype.namespace = function(separator) {
  2.   this.split(separator || '.').inject(window, function(parent, child) {
  3.     return parent[child] = { };
  4.   });
  5. }

And then you can use it via:

javascript

  1. // Default separator is '.'
  2. 'foo.bar.baz.quux'.namespace();
  3.  
  4. foo.bar.baz.quux = 'Nothing special...'; // => "Nothing special..."
  5.  
  6. // Or using a custom one
  7. 'MY_AWESOME_APPLICATION::util::DOM::dimensions'.namespace('::');
  8.  
  9. 'dimensions' in MY_AWESOME_APPLICATION.util.DOM; // => true

Posted by Dion Almaer at 6:56 am
7 Comments

++++-
4 rating from 34 votes

7 Comments »

Comments feed TrackBack URI

Alternatively for those not using Prototype – since namespaces are definitely worth using:

String.prototype.namespace = function(separator) {
var ns = this.split(separator || '.'), p = window;
for (i = 0; i

Comment by remy — February 4, 2008

Doh – code got cut off:

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

Comment by remy — February 4, 2008

We should check if an object is already exist in our namespace chain.
This wont work:


"foo.bar.baz".namespace();
"foo.bar.bay".namespace();
console.log(foo.bar.baz); // undefined

Fixed code:


String.prototype.namespace = function(separator){
this.split(separator || '.').inject(window, function(parent, child) {
var o = parent[child] = parent[child] || { }; return o;
})
}

Comment by aemkei — February 4, 2008

Awesome snippet. I need to use inject() more often.
Here is a pastied cleaner version of the code fix for the bug Aemkei pointed out: http://pastie.caboo.se/147274

Comment by jdalton — February 4, 2008

Alternately this version http://pastie.caboo.se/147291 allows for extending exisitng object namespaces as well as setting a custom separator.

Comment by jdalton — February 4, 2008

It’s a great technique, but it SO doesn’t belong in the String class! Have a function like Namespace.create(‘foo.bar.baz.quux’) that does the same thing and returns a reference to the innermost namespace created.

Comment by sentientholon — February 7, 2008


var Namespace = {
separator: ".",
create: function(space){
return space.split(
Namespace.separator
).inject(
window, function(parent, child) {
return parent[child] = parent[child] || {};
})
}
};

Comment by aemkei — February 11, 2008

Leave a comment

You must be logged in to post a comment.