tags:

views:

42

answers:

1
var foo1 = function () {
   return {
        init: function () {
            alert(this+" hello foo1");
        }
    };
}();

var foo2 = {
    init: function() {
        alert(this+" hello foo2");
    }
};

foo1.init()
foo2.init()

The differences I see are:

  • the first is "closure-style", while the second is not.
  • the first defined a factory function (*) which creates an object and binds the result of this factory to foo1, the second instead is a plain singleton, and you cannot have more instances unless you do .prototype hacking.

Are there any other differences ? this binding behavior ? unexpected browser detonations ? crying kittens ?

(*) In other words, I could do something like

var fooFactory = function () {
   return {
        init: function () {
            alert(this+" hello foo1");
        }
    };
}

var foo=fooFactory();
var bar=fooFactory();

and foo and bar are now two different instances of the same "class" (actually, they are just two Objects that "happen" (by construction) to have the same interface).

+1  A: 

One limitation to foo2 is that you can't really have the notion of private variables. That kind of goes along with the closure details you mentioned, though.

BranTheMan