自 ES2015 以来,在 JS 中创建单例的正确方法是什么? 我知道很多方法,例如:
(() => {
let instance;
class Singleton{
constructor(){
instance = instance || this;
}
}
window.Singleton = Singleton; // or sth to export this class
})();
var a = new Singleton();
var b = new Singleton(); // a is the same as b
但这似乎不是在 Singleton 类中使用“new”运算符的好方法。所以我的问题是是否有一种“正确”的方法在 ES6 中创建单例
最佳答案
这个似乎对我有用:
let instance;
export default class AudioContext {
static getInstance() {
if (!instance) {
instance = {
context:new window.AudioContext() || new window.webkitAudioContext(),
contextCreatedAt: new Date()
}
}
return instance;
}
}
我在不同时间创建了 2 个 AudioContext 实例。然后我检查了 contextCreatedAt 中的时间(返回相同的值)和 context === context 2 - 但是,如果我在这里错了,请详细说明。
关于javascript - 创建单例 ES6 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43169467/