我可以在 javascript 中获取原型的所有实例吗? [英] Can I get all instances for a prototype in javascript?

查看:36
本文介绍了我可以在 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?

像这样:

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.

推荐答案

你可以试试这样的

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

A.instances = [];

之后

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

A.instances中将包含两个创建的对象

in A.instances will contain two created objects

这篇关于我可以在 javascript 中获取原型的所有实例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆