【发布时间】:2018-06-30 04:44:39
【问题描述】:
我看到了使用 ES6 类的单例模式的模式,我想知道为什么我会使用它们而不是仅在文件底部实例化类并导出实例。这样做有什么负面的缺点吗?例如:
ES6 导出实例:
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;
用法:
import API from './services/api-service'
与使用以下单例模式有什么区别?是否有任何理由使用另一个?实际上,我更想知道我给出的第一个示例是否存在我不知道的问题。
单例模式:
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;
用法:
import API from './services/api-service';
let api = new API()
【问题讨论】:
标签: javascript es6-class