正确的方法来创建单独的ES6

时间:2017-04-02 14:28:26

标签: 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

但它似乎不是一种使用" new"的好方法。具有Singleton类的运算符。所以我的问题是,是否有适当的"在ES6中创建单身人士的方法

2 个答案:

答案 0 :(得分:0)

var a = (function () {

  // can put private vars/methods here.
  var a = 3;
  var b = 5;
  var sum = () => a+b;    

  return {// your singleton object
           getSum: sum 
           // ... 
         };

}());

答案 1 :(得分:0)

这个似乎对我有用:

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上检查了时间-但是,如果我在这里错了,请详细说明。