javascriptjavascript-objects

Javascript creating objects - multiple approaches, any differences?


I have seen a few different ways to instantiate objects in javascript, wanted to know the benefits/drawbacks of the various approaches and why you would use one over the other.

Approach 1

var obj = {
    prop: value,
    .
    .
    .
}

Approach one is standard approach, nothing new :)

Approach 2

var obj = new function() {
    var prop1 = value1;
    var fn1 = function() {
    };
    .
    .
    .

    this.prop2 = value2;
    .
    .
    .
}();

The function approach, I wanted to compare this approach with approach 3. The function approach is primarily used for encapsulation (correct?)

Approach 3

var obj = (function() {
    var prop1 = value1;
    var fn1 = function() {
    };
    .
    .
    .

    return {
        prop2: value2,
        .
        .
        .
    }
})();

With this approach, I do not quite see the reasoning behind its usage. How does it differ from approach 2? Both can be used to encapsulate logic.

Is it so we can pass in parameters, so we can deal with any potential conflicts?? E.g jquery's $ syntax - but you can also do this with approach 2...

Thanks.


Edit:


I am aware the approach 1 and 3 are similar (in that they both return objects) however approach 3 also creates a closure. Which approach 2 also does.

That is the basis of my question really, both 2 and 3 create closures, but what is the difference between them.


Solution

  • In approaches #2 and #3 the constructor property of the resulting objects will be different.

    In practice it means that the second approach allows you to instantiate more than one object using the anonymous constructor function:

    x = new function() { alert(1) };
    y = new x.constructor; // shows the message too
    

    The top answer to Module pattern vs. instance of an anonymous constructor includes a quote from Douglas Crockford in which he explains why he thinks the approach #3 is better than #2.