Get all instances of class in Javascript

前端 未结 5 839
再見小時候
再見小時候 2020-12-03 12:19

I thought there would already be an answer for this but I can\'t seem to find one.. How can I run a particular class method on all instances of this class in Javascript?

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 12:35

    You can create a static array and store it on your constructor function:

    MyClass.allInstances = [];
    MyClass.allInstances.push(this);
    

    However, you need some way to figure out when to remove instances from this array, or you'll leak memory.

提交回复
热议问题