The JavaScript blog.


codereview techniques

Using Vars to Shortcut Namespaces

Posted on .

When I was researching the last turing.js
article I came
across a simple technique for namespace shortcuts in TJ Holowaychuk's
jspec. I haven't noticed it used very often, so I thought DailyJS hackers may find it interesting.

;(function() {
  MyClass = {
    map: function(object, callback) {
      var items = [];
      each(object, function(i) { items.push(callback.apply(this, arguments)); });
      return items;

    each: function(object, callback) {
      for (var i = 0; i < object.length; i++) {

  var methods = 'each map'.split(/ /);
  while (methods.length) { eval('var ' + methods[0] + ' = MyClass.' + methods.shift()); }

// Map can refer to each without dereferencing
result = MyClass.map([1, 2, 3], function(i) {
  return i + 1;

// 1,2,3

Ignore the implementations of each and map and
look at the loop after MyClass.

What happens here is a list of methods are mapped to vars so they can be
referenced without their containing object name.

  1. MyClass is declared globally
  2. Methods within the containing anonymous function can refer to
    hand-picked "utility" methods without referring to MyClass
  3. These methods are declared as local variables using
  4. The while loop iterates over each method name

Notice that the loop refers to each method using
methods[0], then methods.shift() when it's
no longer needed, which keeps the loop control simple.

This is useful if you want to cut down code inside a library. It's safe
because the shortcuts are bound to the anonymous function, but novices
may find navigating the code difficult. Tracking down where
each comes from in a big project might be difficult, so
avoid this technique if you're working on a large project with
colleagues with mixed skills.

This is flexible way of achieving similar results to with: