如何动态访问JavaScript子类?

时间:2017-10-26 14:26:21

标签: javascript arrays oop es6-class

我有一个有很多孩子的父类,每个孩子都有非常具体的方法。

我需要遍历数组,基本上每个元素都需要访问不同的子类。有没有办法动态地做到这一点?

我的课程目前看起来像这样:

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
  }
}

所以基本上我有一堆子类,现在我需要一个数组来完成它们。该数组的每个元素都将通过其中一个元素。

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)
    })
  )
}

我该怎么做?

1 个答案:

答案 0 :(得分:1)

我找到了一种适合您需求的方法:

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());
  }
});