JavaScript: loading class methods automatically

In PHP there's a magic method called __autoload() that is used to load automatically one or more classes. JavaScript has no notion of such a method, simply because there's no need to. Anyway, sometimes it's useful to load automatically all the methods of a given class. For example, given the following class:

var Class = {
  
  method1: function() {
   
   alert('Foo');
   
  },
  
  method2: function() {
   
   alert('Bar');
   
  },
  
  method3: function() {
   
   alert('Baz');
   
  }
  
};

If you want to call all the above methods, you have to explicitly call them one by one. We can make this procedure easier with the following function:

function autoload(o) {
  
  for(var i in o) {
   
   if(typeof o[i] === 'function') {
    
    o[i]();
    
   }
   
  }
  
}
 
autoload(Class); // alerts 'Foo', 'Bar', 'Baz'

We use the for ... in loop to iterate over the members of a class passed as an argument to the function. If the member is a function, then we call it. The major drawback with this approach is that this kind of loop is usually slower and more resource-consuming than other JavaScript looping constructs.

Leave a Reply

Note: Only a member of this blog may post a comment.