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.