Return to Snippet

Revision: 25127
at March 21, 2010 09:20 by johnloy


Initial Code
;(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++) {
        callback(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;
});

print(result);
// 1,2,3

Initial URL
http://dailyjs.com/2010/03/19/private-vars-scope

Initial Description

                                

Initial Title
Way in JS to call singleton library methods within a namespace without fully qualifying the namespace in references

Initial Tags
javascript

Initial Language
JavaScript