首页 > 解决方案 > 对 JS 中的所有 Class 实例执行方法

问题描述

假设我有一个类,其方法如下:

class MyClass {

  importantMethod() {
    ... //any code here 
  }

}

假设我有 10/20/更多的类实例,例如:

const inst1 = new MyClass();
const inst2 = new MyClass();
const inst3 = new MyClass();
.... //and more instances here

有没有办法以importantMethod()比以下更优雅的方式在每个实例上执行:

inst1.importantMethod()
inst2.importantMethod()
inst3.importantMethod()
.... //and for all the instances

标签: javascriptclassoop

解决方案


使用forEach

[inst1 , inst2 , inst3].forEach( (item)=> item.importantMethod() ) 

推荐阅读