javascript - 对 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
解决方案
使用forEach
[inst1 , inst2 , inst3].forEach( (item)=> item.importantMethod() )
推荐阅读
- javascript - socket.io 在房间里广播
- sql - 如何在 bigquery 中回填空值?
- c++ - 尝试将字符分配给二维字符数组时,表示数组值的整数在 for 循环中增加
- php - 未定义的数据库变量
- node.js - Heroku 部署失败:无法加载在“package.json”中声明的插件“cypress”:找不到模块“eslint-plugin-cypress”
- javascript - Promisified IndexedDB 事务中的数据操作不会回滚
- python - Django - 多对一关系和用户输入的数据列表
- java - 如何在 Spring Boot Camel 中使用 onException() 处理异常
- c++ - MV Studio C++ - 二维数组不适用于文件
- javascript - 如何将 div 绝对定位在主目录之外?