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

137
Views
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
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!