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
}
}
CodePudding user response:
On Class instantiation (constructor
init), push the current instance to a class's static Array.
Retrieve all your instances by either using <Instance>.method()
or myClass.instances
class myClass {
static instances = [];
constructor(name, password, emailid, id) {
this.name = name;
this.password = password;
this.emailid = emailid;
this.id = id;
myClass.instances.push(this); // Push instance into static Class's property
}
getInstances() {
return myClass.instances; // Return array of instances of same class
}
}
const A = new myClass("Cada", "123", "[email protected]", 1);
const B = new myClass("Roko", "234", "[email protected]", 2);
const C = new myClass("John", "345", "[email protected]", 3);
console.log(A.name, B.name, C.name); // "Cada", "Roko", "John"
console.log(A.getInstances()); // [myClass, myClass, myClass]
console.log(myClass.instances); // [myClass, myClass, myClass]
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.
CodePudding user response:
that ?
class myClass {
constructor(name, password, emailid, id) {
this.Obj = { name, password, emailid, id };
}
asyncMethod = async() => {
return this.Obj
}
}