Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
How to return an array of objects from a method in the same class javascript

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
  }
}

about 4 years ago ยท Juan Pablo Isaza
1 answers
Answer question

0

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", "c@c.c", 1);
const B = new User("Roko", "234", "r@r.r", 2);
const C = new User("John", "345", "j@j.j", 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:"c@c.c", id:1});
const B = new User({name:"Roko", password:"234", emailid:"r@r.r", 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] ๐Ÿ˜Ž

about 4 years ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!