Posted By

johnloy on 03/21/10


Tagged

javascript


Versions (?)

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


 / Published in: JavaScript
 

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

  1. ;(function() {
  2. MyClass = {
  3. map: function(object, callback) {
  4. var items = [];
  5. each(object, function(i) { items.push(callback.apply(this, arguments)); });
  6. return items;
  7. },
  8.  
  9. each: function(object, callback) {
  10. for (var i = 0; i < object.length; i++) {
  11. callback(i);
  12. }
  13. }
  14. }
  15.  
  16. var methods = 'each map'.split(/ /);
  17. while (methods.length) { eval('var ' + methods[0] + ' = MyClass.' + methods.shift()); }
  18. })();
  19.  
  20. // Map can refer to each without dereferencing
  21. result = MyClass.map([1, 2, 3], function(i) {
  22. return i + 1;
  23. });
  24.  
  25. print(result);
  26. // 1,2,3

Report this snippet  

You need to login to post a comment.