Singleton Pattern in ES6 and ES7

export default class Singleton {

  static instance;

      return instance;

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



let first = new Singleton();
let second = new Singleton();

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


Already added
$npm install --save babel-preset-es2016 and
.babelrc has

"presets": ["es2016"]

But still 'Missing class properties transform.'

Posted by Sebastian Cheung on September 13, 2016 at 11:15 PM CEST #

Doesn't work. The code written above gives this error: 'instance isn't defined'.

Posted by Ahmed Khaled on March 14, 2020 at 11:31 AM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments