Javascript – object initializer


I've realized you can have a property in an object run automatically like this:

var obj = {

    init:(function(){ alert('loaded');})();


I'm trying to use this method as an initializer for the object. The problem I'm running into is passing a reference to 'obj' to the init property. I suspect it generates errors because the obj hasn't been completely built in browser yet. I'm trying to do the following, but unsuccessfully. If there's a way to do this, I'd love to know how.

var obj = {
    prop:function(){ alert('This just ran.'); },
    init:(function(){ obj.prop(); })();

Best Solution

If you want to create multiple instances of similar objects, you should use plain old constructor functions (remember to put shared properties in the prototype!).

If you want to create a single object, consider using an anonymous constructor. Your example would read:

var obj = new (function() {
    this.prop = function() {
        alert('This just ran.');

    // init code goes here:

This has an additional benefit over object literals: the constructor function can be used as a closure over 'private' variables.

Don't overuse object literals: they may make simple things simple, but complex things will get overly complicated.