Reputation: 31
I am new to javascript. I want a class method to return an array of objects instantiated by the same class. How to do that?
Currently,Basically the following is the general structure my code in question.
class myClass{
constructor(name,password,emailid,id) {
this.name = name;
this.password = password;
this.emailid = emailid;
this.id = id;
}
asyncMethod = async()=> {
//method returns array of objects of same class
}
}
Upvotes: 2
Views: 1235
Reputation: 206121
On Class instantiation (constructor
init), push the current instance to a class's static Array.
Retrieve all your instances by either using userInstance.getInstances()
(← this is bad practice! Read further) or User.instances
class User {
static instances = [];
constructor(name, password, emailid, id) {
this.name = name;
this.password = password;
this.emailid = emailid;
this.id = id;
User.instances.push(this); // Push instance into static Class's property
}
getInstances() {
return User.instances; // Return array of instances of same Class
}
}
const A = new User("Cada", "123", "[email protected]", 1);
const B = new User("Roko", "234", "[email protected]", 2);
const C = new User("John", "345", "[email protected]", 3);
console.log(A.name, B.name, C.name); // "Cada", "Roko", "John"
console.log(A.getInstances()); // [User, User, User]
console.log(myClass.instances); // [User, User, User]
Closely related answer: https://stackoverflow.com/a/61014433/383904
And I could not explain the static
keyword better than MDN:
Neither static methods nor static properties can be called on instances of the class. Instead, they're called on the class itself. (*ac:
myClass.instances
in the above demo)
Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances.
It's usually a bad practice to expose internals of a Class to an Instance.
For Example, a User instance should not be able to inherit from its Class constructor the entire list of Users.
Here's a slight variant that uses Static Private #
and Class Getters get
:
class User {
static #_instances = []; // Static and private
constructor(userData) {
Object.assign(this, userData);
User.#_instances.push(this);
}
static get instances() { // Static to Class
return [...User.#_instances]; // exposes private (as immutable)
}
}
const A = new User({name:"Cada", password:"123", emailid:"[email protected]", id:1});
const B = new User({name:"Roko", password:"234", emailid:"[email protected]", id:2});
console.log(A.name, B.name); // "Cada", "Roko",
console.log(A.instances); // undefined 😭
console.log(User.instances); // [User, User] 😎
User.instances.push({name:"EVIL!"}); // 😈
console.log(User.instances); // [User, User] 😎
Upvotes: 4