Skip to content

Instantly share code, notes, and snippets.

@gr0uch
Last active May 29, 2018 09:44
Show Gist options
  • Save gr0uch/0c26cf13b26e5f9655ec to your computer and use it in GitHub Desktop.
Save gr0uch/0c26cf13b26e5f9655ec to your computer and use it in GitHub Desktop.
Reconciling ES6 `class` and constructor anti-pattern.

The use of the new keyword in JavaScript is highly divisive, some say that you should avoid it entirely. ES6 classes may seem at odds with this line of thinking, but I will show how you can have your cake and eat it too. Consider a module that exports a class:

export default class {
  constructor () { /* Do stuff here. */ }
}

The only way to get an instance out of this module, or rather an object that inherits the prototype of the class object, is to use the new keyword, which some consider harmful. Personally, I am not against new, it provides implicit understanding that the returned value is an object with inherited properties.

The solution for those who are against new is extremely simple. Just add a static method that proxies the constructor method:

export default class {
  constructor () { /* Do stuff. */ }
  static create () { return new this(...arguments) }
}

For those who want to use the class implementation, new works as expected, and for those who are against it can call the create static method, which hides the class implementation from the consumer. The method signature of the static "constructor" method is exactly the same as the class constructor method, by using the spread operator on the arguments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment