Reputation: 7113
QUESTION: Is there any difference in the resulting object obj
of the two examples below?
Closure example:
var myClosure = function(paramId) {
return {
Id : paramId,
getId : function() {console.log(this.Id)},
setId : function(sId) {this.Id = sId}
};
}
var obj = myClosure(2);
obj.getId();//outputs 2
obj.setId(5);
obj.getId();//outputs 5
Constructor example:
var MyConstr = function(Id)
{
this.Id = Id;
this.getId = function() { console.log(this.Id)};
this.setId = function(sId) {this.Id = sId};
}
var obj = new MyConstr(2);
obj.getId();//outputs 2
obj.setId(5);
obj.getId();//outputs 5
I understand that it is best practice to use a Constructor to create objects, since that is its essential purpose, and would confuse future code readers less. My questions purpose here is out of curiosity. Is there some sort of a difference in the end result? Be it with the object, or the memory usage, or something else?
Upvotes: 4
Views: 818
Reputation: 73938
In this example there are no differences, but you could fine different usage in real world application.
The closure example is usually used for [The Module Pattern][1] or [The Revealing Module Pattern][2].
The constructor example is usually used for the [The Constructor Pattern][3] and [The Prototype Pattern][4] pattern.
In your case I would suggest using the The Prototype Pattern as currently you are adding getId
and setId
function to each new object created, when instead you could save some memory adding to the prototype.
Also you should consider using JavaScript getter and setter for instead of getId
and setId
.
Upvotes: 1
Reputation: 6561
Both object will have the same own properties and methods. However, the one constructed with new MyConstr
will have its [[proto]] referencing MyConstr.prototype, allowing it to inherit methods and properties.
You're not using those features so it makes no difference in your case, but you should actually define setId
and getId
on the prototype, which would save memory (no more copying the methods on each instance) and a little time (the constructor would do less work).
Additionally, constructing an instance will allow you to use the instanceof
operator.
Upvotes: 2