Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/461.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何动态访问JavaScript子类?_Javascript_Arrays_Oop_Es6 Class - Fatal编程技术网

如何动态访问JavaScript子类?

如何动态访问JavaScript子类?,javascript,arrays,oop,es6-class,Javascript,Arrays,Oop,Es6 Class,我有一个父类和一群子类,每个子类都有非常具体的方法 我需要遍历数组,基本上每个元素都需要访问不同的子类。有什么方法可以动态地做到这一点吗 我的课程目前如下所示: export default class MyParent { constructor (something) { // do constructor things } someMethod(param) { // do something } } . . . export default 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)
    })
  )
}

我如何才能做到这一点?

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

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

您是否尝试过将所有子类放入一个数组中,每个子类都使用“[new childClass1(),new childClass2()]”等进行调用?在每个循环中循环,例如.forEach循环,并尝试在每次迭代中调用一个方法。或者将所有子类插入数组,并在每次迭代时应用“new childClass()”以及块内的方法执行,以检查子类的数据