In trying to built a object with a inner propriety in the constructor function that keeps the array with all the objects created with the same constructor.
I’m thinking that the best way would be with a closure on object initialization and this is how I try to solve this:
function myObject (name){
this.name=name;
this.allInstances = [];
}
myObject.ptototype = {
init : function(){
return function(){this.allInstances.push(this.name)};
}(),
}
object1 = new myObject("object1");
object2 = new myObject("object2");
console.log(object1.allInstances); // should print ["object1", "object2"]
Does anyone know how to achieve that ? Is that even possible ?
I’m specifically trying to get a solution which uses only function constructor and prototype to achieve that.
I know how to solve that by pushing the proprieties to an external array, like:
var allInstances = [];
function myObject (name){
this.name=name;
allInstances.push(this.name);
}
console.log(allInstances)
Place the Array as a property on the
prototype, and it will be shared among all instances:Or if you want the Array to be more protected, use a module pattern, and include a function on the prototype to return the Array.