JavaScript: object initialization study

Object initialization is surely among the most requested features in OOP with JavaScript. JavaScript has no constructor methods like PHP, so we need to take inspiration from existing JavaScript frameworks, such as Prototype. This library provides an initialize() method to be used with any new object that is being created. I've tried to emulate this behavior but I found only a quick-and-dirty solution that works with objects that make use of the functional constructor patter. Here's the code:

var Class = new function() {



   this.foo = null;
   this.bar = null;
   
   this.init = function() {
   
     this.foo = 'Foo';
     this.bar = 'Bar';
   
   
   }
   
   
   return this.init();





}

Testing everything out:

alert(Class.foo); // 'Foo'

It works, but it's clunky and has several disadvantages. First, other methods and properties that may use the values of the initialized properties won't benefit of them because the return statement prevents this from happening. Further, this workaround doesn't work with object literals. I will test more extensively this feature by dissecting the core of Prototype in order to find the correct procedure to be used.

Leave a Reply

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