0

I have a parent class with a bunch of children, each with very specific methods.

I need to loop through the array and basically each element will need to access a different child class. Is there any way to do this dynamically?

My classes currently look like this:

export default class MyParent {
  constructor (something) {
    // do constructor things
  }

  someMethod(param) {
    // do something
  }
}
.
.
.
export default class MyChildClass extends MyParent {
  constructor (something) {
    super(something)
  }

  someMethod(param) {
    // do something in overwritten method
  }
}

So basically I have a bunch of child classes, and now I need an array to go through them. Each element of that array will go through a different one of them.

export default function goThroughClasses (myArray) {
  const parentClass = new ParentClass(something)
  return myArray.map(arr => {
    // I would like this to go through all the different child methods instead of just the parent class
    // Note: the array does have data which would indicate which one
    // it should go through
    return parentClass.someMethod(arr)
    })
  )
}

How can I do this?

1
  • Have you tried putting all of the child classes into an array, each invoked with "[new childClass1(), new childClass2()]", etc. ? Looping through each such as a .forEach loop and try invoking a method on each iteration. Or insert all child classes into the array and on each iteration apply a "new childClass()" along with a method execution inside the block to check for data of the child class Commented Oct 26, 2017 at 14:29

1 Answer 1

1

I found an approach that can fit to your needs:

class Color {
  constructor(name) {
    this.name = name;
  }

  showColor() {
    return this.name;
  }
}

class Scent {
  constructor(name) {
    this.name = name;
  }

  showScent() {
    return this.name;
  }
}

const arr = [Color, Scent];

arr.forEach((childClass) => {
  const Child = new childClass('something here');
  if (Child.showColor) {
    console.log(Child.showColor());
  } else if (Child.showScent) {
    console.log(Child.showScent());
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.