I have defined pure objects in JS which expose certain static methods which should be used to construct them instead of the constructor. How can I make a constructor for my class private in Javascript?
var Score = (function () {
// The private constructor
var Score = function (score, hasPassed) {
this.score = score;
this.hasPassed = hasPassed;
};
// The preferred smart constructor
Score.mkNewScore = function (score) {
return new Score(score, score >= 33);
};
return Score;
})();
Update: The solution should still allow me to test for x instanceof Score. Otherwise, the solution by @user2864740 of exposing only the static constructor works.
classand#constructoryou will getSyntaxError: Class constructor may not be a private method(v8) andSyntaxError: bad method definition(SpiderMonkey). Because of this, I assume private constructors are not meant to be part of JS/ES. If you wanted to create a singleton, you could create a private fieldstatic #instance = null, in constructorif (YourClass.#instance instanceof YourClass) return YourClass.#instance // or throw error perhaps