简体   繁体   English

我可以在javascript中获取原型的所有实例吗?

[英]Can I get all instances for a prototype in javascript?

It is easy to get the prototype of an object, but is there any way to get all the instances that has a specific prototype? 获取对象的原型很容易,但有没有办法获得具有特定原型的所有实例?

Something like this: 像这样的东西:

var allAnimals = Animal.prototype.getInstances();

One could write custom code to keep track of instantiated objects, but I'm interested in whether there is any build-in method for this. 可以编写自定义代码来跟踪实例化对象,但我对是否有任何内置方法感兴趣。

you can get instances that have created on window like this 你可以得到像这样在窗口上创建的实例

var o = [];
(for i in window)
{
    if(window[i] instanceof Animal) o.push(window[i]);
}

but this code, doesn't get instances which have not been created on window... you can create a method on Animal to create instance from that, and save it in a collection: 但是这段代码没有得到在窗口上没有创建的实例......你可以在Animal上创建一个方法来创建一个实例,然后将它保存在一个集合中:

 +function () {

        var AnimalInstances = [];
        Animal = function (flag) {

            if (!flag) throw new Error("Invalid Instantiation");
        };
        Animal.Create = function () {

            var o = new Animal(true);
            AnimalInstances.push(o);
            return o;
        };
        Animal.GetInstances = function () {

            return AnimalInstances;
        };
    }();

or : 要么 :

+function () {

        var AnimalInstances = [];
        Animal = function () {

            AnimalInstances.push(this);
        }
        Animal.GetInstances = function () {

            return AnimalInstances;
        };
    }();

You can try something like this 你可以尝试这样的事情

function A(f){
    this.field = f;
    A.instances.push(this);
}

A.instances = [];

so after 所以之后

var one = new A(10), two=new A('123');

in A.instances will contain two created objects A.instances中将包含两个创建的对象

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

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