简体   繁体   中英

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:

 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 = [];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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