Adam Bien's Weblog

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 JavaScript Bootstrap or Building Apps with React!


NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 7: Bootstrap, Effective, Architectures, Web, React and Angular, Testing and Microservices

Newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

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 #

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License