抽象类方法调用的for-of循环

Abstracting for-of loop out of class method calls

本文关键字:for-of 循环 调用 抽象类 类方法 抽象      更新时间:2023-09-26

我正在使用一个类,其中每个方法都在同一个列表上操作,但是,我正在寻找一种有效的方法来抽象出每个方法体的循环特性,因为它几乎存在于每个块中。

例如,目前我正在做这样的事情:

class example {
  constructor(list) {
  ....
  }
  ....
  someFunc(param) {
    for (let elem of this.list) {
      elem.doSomething();
    }
  }
  someOtherFunc(param) {
    for (let elem of this.list) {
      elem.doSomethingElse();
    }
  }
}

理想情况下,我希望能够在不使用for of循环的情况下调用这些方法,因为它会导致冗余代码。我想知道我是否可以通过其他方式实现这个目标?

是的,您可以从Array.prototype.forEach()中获得灵感,并为您的对象实现.each()方法:

class example () {
    each(callback) {
        for (let elem of this.list) {
            callback(elem);
        }
    }
    someFunc(param) {
        this.each(x => x.doSomething());
    }
}

如果list实现了一个数组,你只想做上面的简单循环,那么有更好的消息,它已经为你实现了Array.prototype.forEach():

class example () {
    someFunc(param) {
        this.list.forEach(x => x.doSomething());
    }
}

自定义.each()实现当然允许您在for循环中做其他事情,因此您可以抽象出更多的代码。