在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

用于每个

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

我假设您希望能够在任何给定时刻碰巧存在的类的所有实例上运行函数(在任何时间,可能多次(。YOu可以通过模拟类实例的"私有静态"列表来实现这一点。每个实例都被添加到类的constructor调用的列表中,您可以提供一个函数来迭代这个列表:

let MyClass;
{
// this is only visible to functions inside the block
let myClassInstances = [];
MyClass = class {
constructor() {
myClassInstances.push(this);
}
importantMethod() {
console.log(this);
}
}
MyClass.runImportantMethodOnAll = function() {
myClassInstances.forEach(inst=>inst.importantMethod());
}
};

你可以这样使用:

let x = new MyClass();
let y = new MyClass();
MyClass.runImportantMethodOnAll();

也不需要将runImportantMethodOnAll连接到MyClass。你可以把它存放在任何地方。

我认为您有两个选项:

  1. 如果这可以在初始化时运行,并且不会引发错误等,并且是安全的,那么你可以在构造函数中运行它,因此每次出现新实例时,它都会调用它…不是最佳实践,但可能。。。。

  2. 做一些类似的事情

const instances = [];
for (let i=0; i<20; i++) {
const classInstance = new MyClass();
classInstance.ImportantFunction();
instance.push(classInstance);
}

这也是一种黑客攻击,但如果你有很多实例,它可能会让代码更干净。。。

如果你关心命名实例,那么你可以将上面例子中的数组更改为一个对象,并将每个带有命名键的实例放在对象中,这样访问实例就会更容易。

至少从我的知识来看,不幸的是,我不熟悉类实例化的任何"挂钩"。

最新更新