Home > database >  storing all created child classes in a array in Parent Class?
storing all created child classes in a array in Parent Class?

Time:08-13

is there a way to make that every created Child class with the new keyword, be automatically added to an array in the parent Class?

so we can use that array to loop on it or filter it, on applying some logic.

(with functional programming is easy this thing, but class base programming seems that the array isn't working)


what I want?

creating a array like this (in class parent)

[new Child(), new Child(), new Child()]

I have a pretty long code, but since I am asking on StackOverflow,
I created a mini-example for you so you can understand:

class Parent {
  constructor() {
    this.array = [];
  }

  displayArray() {
    console.log(this.array);
  }
}

class Child extends Parent {
  constructor() {
    super();
    // "this" is new Child()
    // BUG: it don't push nothing 
    Parent.array.push(this);
    
    // console.log(Parent.array)
  }
}

// here I create 3 copies (as a example)
new Child();
new Child();
new Child();

// here the Parent Array need to be like this:
// this.array = [new Child(), new Child(), new Child()];
new Child();

// so I can do some loops and stuff with that array...

CodePudding user response:

The array should be a static property, not a per-instance property. And you should push into it in the Parent constructor, so that it will collect instances of all subclasses, not just Child.

class Parent {
  static array = [];
  constructor() {
    Parent.array.push(this);
  }

  displayArray() {
    console.log(this.array);
  }
}

class Child extends Parent {
  constructor() {
    super();
  }
}

// here I create 3 copies (as a example)
new Child();
new Child();
new Child();
new Child();

console.log(Parent.array);

CodePudding user response:

You can pass the parent as an argument to the child's constructor, and have that constructor pass the child to a method of the parent which adds it as a child:

class Parent {
    constructor() {
      this.array = [];
    }
  
    addChild(child) {
        this.array.push(child)
    }
  }
  
  class Child extends Parent {
    constructor(parent) {
      super();
      // "this" is new Child()
      parent.addChild(this);
      
      // console.log(Parent.array)
    }
  }

In your example, you are trying to call the method on Parent, which is a class. You want to call it on an object of that class, by passing that object to the child. To do this with the above code, we have:

  let parent = new Parent();
  let child = new Child(parent);
  • Related