exist
exist

Reputation: 67

How do I get the object created during a constructor?

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

Answers (3)

Mostafa El-Messiry
Mostafa El-Messiry

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

Matt Coarr
Matt Coarr

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

Jonas Wilms
Jonas Wilms

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

Related Questions