I want to encapsulate an "object factory" in the revealing module pattern to conceal variables, etc, from the rest of my program. Do objects created by my module share the same prototype
instance? I.e., am I creating a new prototype
object in memory each time I create a new object with my factory, or do all the objects share/"see" the same prototype?
Here is a simplified example of my code:
var Factory = (function(){
var uid_seed = 0;
function TestObject() {
this.size = 1;
this.name = "foo";
this.uid = uid_seed++;
}
TestObject.prototype.getName = function() {
return "Name is: " + this.name;
};
return {
testObject: function() {return new TestObject();}
}
})();
var arr = [];
for (var i = 1000; i--;) arr.push(Factory.testObject());
When I create 1000 TestObject
objects in the last line of this code, do they each have a prototype that is consuming memory? Or is this a memory-efficient way of creating objects with a shared prototype?
Yes, they do have the same prototype. The module initialisation code is executed only once, and only one prototype is created. You'd also expect that they all get different uid
s instead of re-evaluating uid_seed = 0
for every instance, right?
You can test that easily by checking Object.getPrototypeOf(arr[0]) === Object.getPrototypeOf(arr[1])
.