adam bien's blog

Singleton Pattern in ES6 and ES7 📎


export default class Singleton {

  static instance;

  constructor(){
    if(instance){
      return instance;
    }

    this.state = "duke";
    this.instance = this;
  }

}

Now:


let first = new Singleton();
let second = new Singleton();
console.log(first===second);

//output: true

The code above uses ECMAScript 2015/ES6 (classes) and ECMAScript 2016/ES7 (static fields) features. It transcompiled, "old school" ES5 representation looks like:


	function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

	var Singleton = function Singleton() {
	  _classCallCheck(this, Singleton);

	  if (instance) {
	    return instance;
	  }

	  this.state = "duke";
	  this.instance = this;
	};

	exports.default = Singleton;

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.