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.