Get all instances of class in Javascript

前端 未结 5 837
再見小時候
再見小時候 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:48

    Sorry for such a late reply, but I found myself trying to achieve this and I think this may be a simpler answer.

    Say you want all instances of class MyClass, only get instances created at top window level (not including instances created inside a closure):

    for (var member in window)
    {
        if (window[member] instanceof MyClass)
            console.info(member + " is instance of MyClass");
    }
    

提交回复
热议问题