javascript - 创建单例 ES6 的正确方法

标签 javascript ecmascript-6 singleton

自 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/

相关文章:

javascript - 无法在普通 JS 中导出类

c++ - 不是全局单例设计模式?

java - 我可以在 Java 中使用除法结果设置最终变量吗?

javascript - 在 TypeScript 中使用时,ES6 功能是否编译为 ES5?

javascript - 你能选择用 Babel 转译哪些 ES6 特性吗?

c++ - 通过 C++ 中的静态实例的单例——进入源文件或头文件?

javascript - 跨域子弹出窗口关闭时可以重新加载页面吗? IE7+

javascript - 如何在更改事件中获取剑道组合框的值

javascript - Handsontable-慢速粘贴

javascript - jquery div hidden and show,如何控制show div的位置?