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

140
Vistas
Javascript inheritance singleton pattern and static properties and parent class

I'm asking myself a question about inheritance and static properties in javascript.

here is my code:

export default class BaseService {
  static singleton = null;
  _instance;

  constructor() {
    this._instance = axios.create({
      baseURL: process.env.REACT_APP_SERVER_URL,
      headers: {
        'Accept': "application/json",
        'Content-Type': "application/json"
      }
    });
  }
}

export default class AService extends BaseService{
    
    constructor() {
        super();
    }

    static getInstance() {
        if (AService.singleton == null) { 
            AService.singleton = new AService();
        }
        return AService.singleton;
    }
}

export default class BService extends BaseService{
        
        constructor() {
            super();
        }
    
        static getInstance() {
            if (BService.singleton == null) { 
                BService.singleton = new BService();
            }
            return BService.singleton;
        }
    }

So, in my code instead of making a service = new AService() each time i need the corresponding service i go with the getInstance() method. I did few tests and it seems to work as expected, but i need some confirmations from more experienced js developers.

Knowing the fact AService and BService are differents objects types means when i create an instance of AService the singleton from the parent object is set only for all the AService objects and not the BService?

The second part of my question is: is this a good pattern implementation for singleton in es6 classes?

The last part is if it is the case it is possible to put the getInstance method on the parent class, like in c# i would do something like that: getInstance<T>() where T : BaseService meaning the generic T type is BaseService or inherit from BaseService.

Thanks in advance, i hope i'm understandable don't hesitate to ask me more information in the other case.

about 4 years ago · Juan Pablo Isaza
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