Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

146
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda