Reputation: 58
I have a use case as follows
var myObject1 = new myObject();
and myObject should have an array which will store all the objects created of this myObject
Example:-
if create an object such as
var xyz = new myObject();
myObject.all[0] == xyz
is there any way where - when I create an object & I can push it into an array which is in the definition of same object.
Upvotes: 0
Views: 45
Reputation: 150030
You can create a property directly on the constructor function, to get the myObject.all[0] == xyz
behaviour mentioned in the question. Add each object to the array from within the constructor:
function MyObject() {
MyObject.all.push(this);
// any other initialisation tasks here
}
MyObject.all = [];
var obj1 = new MyObject();
var obj2 = new MyObject();
// to access the array use MyObject.all:
console.log(MyObject.all[1] === obj2); // true
Alternatively, you can add an array to the object prototype, but still add new objects to that array from within the constructor:
function MyObject() {
this.all.push(this);
// any other initialisation tasks here
}
MyObject.prototype.all = [];
var obj1 = new MyObject();
var obj2 = new MyObject();
// to access the array:
console.log(obj1.all);
// or
console.log(MyObject.prototype.all);
console.log(obj1.all[1] === obj2); // true
(Note: in both examples, I've spelled MyObject
with a capital "M", because it is a JS convention for functions intended as constructors to be capitalised. This isn't mandatory.)
Upvotes: 4
Reputation: 23171
Maybe something like this?
function MyObject(name){
if (!O.prototype.instances) O.prototype.instances = [];
O.prototype.instances.push(name);
}
var a = MyObject('a');
var b = MyObject('b');
console.log(MyObject.prototype.instances)
Upvotes: 0