Reputation: 67
Beginner question here. I am trying to use the class syntax in javascript to make an object. I want to add the object as whole to an arraylist when it is created. I would also like to loop through that array later. My question: how do I add the actual object created in the constructor. Example code:
class Example {
constructor(x,y,z) {
this.x = x;
this.y = y;
this.z = z;
}
}
Ideally I want to, when an Example object is created, add it to an array of examples. Can I do this within the constructor function? Also, if I have an array of Examples: what is the correct syntax for for in looping through it.
var examples = []
for Example in examples
Upvotes: 0
Views: 41
Reputation: 380
the constructor can simply add the object like this
var examples = []
class Example {
constructor(x,y,z) {
this.x = x;
this.y = y;
this.z = z;
examples.push(this)
}
}
Upvotes: 2
Reputation: 935
this is a little strange, but you should be able to add this line to the bottom of your constructor:
examples.push(this);
Upvotes: 0
Reputation: 138567
Just push it into an array:
class Example {
constructor() {
Example.instances.push(this);
}
}
Example.instances = [];
And you can iterate that like:
for(const instance of Example.instances) {
//...
}
Upvotes: 2