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


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  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

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.