A couple of months ago I created a simple autoloading method to be attached to any JavaScript class. The major drawback with this approach is that all methods are actually loaded, following the source code order. What if we want to change that order by creating a precedence in the code execution? For that reason I decided to create an improved version of my autoload()
method. Now this method also accepts an array of class methods to be executed in the specified order. The code is as follows:
var Class = { property: 'Test', method1: function() { alert(Class.property + ' 1'); }, method2: function() { alert(Class.property + ' 2'); }, method3: function() { alert(Class.property + ' 3'); }, autoload: function(methods) { methods = methods || []; var i, len = methods.length; if(len !== 0) { for(i = 0; i < len; i += 1) { methods[i](); } } else { for(var j in this) { if(typeof this[j] === 'function' && this[j] !== arguments.callee) { this[j](); } } } } };
If no array is provided, then this method will execute all the methods contained within a given class. An example:
window.onload = function() { Class.autoload([Class.method3, Class.method2, Class.method1]); };
You can see a demo below.