繁体   English   中英

在JS中的所有Class个实例上执行一个方法

[英]Executing a method on all the Class instances in JS

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

class MyClass {

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

}

假设我有 10/20/更多个 Class 实例,例如:

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

我认为你有两个选择:

  1. 如果这可以在初始化时运行并且不抛出任何错误等并且是安全的,您可以在构造函数中运行它,因此每次有一个新实例时它都会调用它......不是最佳实践但可能......

  2. 做类似的事情

const instances = [];

for (let i=0; i<20; i++) {
  const classInstance = new MyClass();

  classInstance.ImportantFunction();
  instance.push(classInstance);
}

这也是一种黑客攻击,但如果您有很多实例,它可能会使代码更清晰一些......

如果您关心命名实例,那么您可以将上面示例中的数组更改为 object 并将每个具有命名键的实例实际放入 object 中,然后访问这些实例会更容易。

至少据我所知,不幸的是,我不熟悉 class 实例化上的任何“钩子”。

我假设您希望能够在任何给定时刻恰好存在的 class 的所有实例上运行 function(在任何时候,并且可能多次)。 你可以通过模拟 class 实例的“私有静态”列表来做到这一点。每个实例都会在类的constructor调用中添加到列表中,你可以提供一个 function 来迭代这个列表:

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 你可以把它存放在任何地方。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM