简体   繁体   English

如何在 Javascript 中的对象构造函数中创建数组

[英]How to Create an Array within an Object Constructor in Javascript

I am trying to be able to make a list of all instances of a Constructor, so I can check if all of these fit criteria in an IF statement For Example:我试图能够列出一个构造函数的所有实例,这样我就可以在 IF 语句中检查所有这些合适的标准,例如:

 function People() { People.allInstances = []; People.allInstances.push(this); } var Carry = new People(); var Gary = new People(); var Parry = new People(); console.log(People.allInstances);

However, I seem to lose all data except for the last instance I created.但是,除了我创建的最后一个实例之外,我似乎丢失了所有数据。 How can I make that list/array, and then use that array to test if any of them has a certain property?如何制作该列表/数组,然后使用该数组来测试它们中的任何一个是否具有某个属性?

The constructor runs every time an instance is constructed with it, but you only want to create an empty array once:每次使用它构造实例时,构造函数都会运行,但您只想创建一次空数组:

function People() {
    People.allInstances.push(this);
}

People.allInstances = [];

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

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