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() { = null; = null;
   this.init = function() { = 'Foo'; = 'Bar';
   return this.init();


Testing everything out:

alert(; // '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.