Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda