Thursday, May 23, 2024
27
rated 0 times [  33] [ 6]  / answers: 1 / hits: 44247  / 11 Years ago, fri, april 19, 2013, 12:00:00

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.


More From » javascript-objects

 Answers
0

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.


[#78773] Thursday, April 18, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kennedi

Total Points: 702
Total Questions: 109
Total Answers: 111

Location: Vietnam
Member since Sun, Oct 18, 2020
4 Years ago
;