I have implemented a Store
class which comes with a static factory
method Store.create()
, and I don’t want users to call the store’s
constructor directly:
1'use strict';
2
3class Store {
4 constructor (id) {
5 this._id = id;
6 }
7
8 static create (id) {
9 return new Store (id);
10 }
11}
12
13module.exports = Store;
Ideally, I’d like to make constructor()
private, but this concept
does not exist in ES2015. So if I can’t hide the constructor, I want
to forbid any direct calls. And tell the user what to do instead, if
she does indeed mistakenly call new Store()
.
Check who’s calling
Here is the solution I have come up with:
1'use strict';
2
3const secret = {};
4
5class Store {
6 constructor (id, key) {
7 if (key !== secret) {
8 throw new Error ('Do not use new Store(): call Store.create() instead')
9 }
10 this._id = id;
11 }
12
13 static create (id) {
14 return new Store (id, secret);
15 }
16}
17
18module.exports = Store;
The constructor will only work if the caller passes in the expected
secret
. And since the object is only visible from inside the module,
it cannot be passed in accidentally ({}
is not equal to secret
in
the !==
comparison).