I see templates that use a singleton template using ES6 classes, and I wonder why I will use them, and not just create an instance of the class at the bottom of the file and export the instance. Is there any negative flaw for this? For instance:
ES6 Export Instance:
import Constants from '../constants';
class _API {
constructor() {
this.url = Constants.API_URL;
}
getCities() {
return fetch(this.url, { method: 'get' })
.then(response => response.json());
}
}
const API = new _API();
export default API;
Application:
import API from './services/api-service'
What is the difference from using the following Singleton template? Are there any reasons to use one of the other? I am really curious to find out if the first example I gave can be problems that I donβt know about.
Singleton:
import Constants from '../constants';
let instance = null;
class API {
constructor() {
if(!instance){
instance = this;
}
this.url = Constants.API_URL;
return instance;
}
getCities() {
return fetch(this.url, { method: 'get' })
.then(response => response.json());
}
}
export default API;
Application:
import API from './services/api-service';
let api = new API()
Aaron source
share