【问题标题】:Executing a method on all the Class instances in JS对 JS 中的所有 Class 实例执行方法
【发布时间】:2020-04-24 16:41:28
【问题描述】:

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

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

【问题讨论】:

    标签: javascript class oop


    【解决方案1】:

    使用forEach

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

    【讨论】:

      【解决方案2】:

      我假设您希望能够在任何给定时刻碰巧存在的类的所有实例上运行一个函数(在任何时候,并且可能多次)。您可以通过模拟类实例的“私有静态”列表来做到这一点。每个实例都会在类的 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。您可以将其存储在任何地方。

      【讨论】:

      • 真的太棒了!谢谢!
      【解决方案3】:

      我认为你有两个选择:

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

      2. 做类似的事情

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

      这也是一种 hack,但如果您有很多实例,它可能会使代码更简洁...

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

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

      【讨论】:

        猜你喜欢
        • 2013-12-08
        • 1970-01-01
        • 1970-01-01
        • 2011-11-24
        • 1970-01-01
        • 2015-06-09
        • 2014-02-22
        • 2020-07-05
        • 2018-02-19
        相关资源
        最近更新 更多