JavaScript: the autoload method

I've done a couple of tests about the remote but still interesting possibility of creating an autoload method for JavaScript classes. The solution I've found so far is still incomplete because it doesn't take into account the case of methods with parameters. Also, it doesn't take into account the possibility of changing the order in which all the methods are being executed, thus limiting ourselves only to the source code order. Anyway, here it is:

var Class = {
  
  foo: 'Foo',

  bar: 'Bar',

  method1: function() {

    alert(this.foo);

  },

  method2: function() {

    alert(this.bar);
  
  },

  autoload: function() {

    for(var i in this) {

      if(typeof this[i] === 'function' && this[i] !== arguments.callee) {

          this[i]();

      }


    }
  }

}

Class.autoload(); //  alerts 'Foo', 'Bar'

The arguments.callee reference is used here to make sure that this method doesn't create an infinite loop, that is, calling every method and itself.

One thought on “JavaScript: the autoload method”

  1. Java may be the main choice for enterprise development now, but it’s days are numbered as the only stalwart option to go with.

    Let’s face it, many of these so called “enterprise applications” could easily have been written much faster and with less overhead using technologies like Python, PHP, et al.






    ruby training

Leave a Reply

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