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

123
Vistas
Javascript - Class - Method Returning Undefined When Calling Constructor Property

I'm currently learning Javascript. When I run the following code, I am getting undefined. Not sure what is wrong. Everything seems to be fine. Any help will be appreciated. Thank you.

class User{
  constructor(){
    this.array = [1, 2, 3]
  }

  static getNumber(){
    return console.log(this.array)
    
  }
}


User.getNumber()

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

First of all, you have to create a new instance of User with new User() or new User if you want to be able to access instance properties (such as array), because they are created with this.array = .... From the Mozilla Web Docs:

The static keyword defines a static method or property for a class, or a class static initialization block (see the link for more information about this usage). Neither static methods nor static properties can be called on instances of the class. Instead, they're called on the class itself.

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.

Because getNumber is called on the constructor itself, it doesn't have access to any of the instance properties (the only one is this.array). When new User is called, it creates the this.array, but only for the instance, not the constructor.

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