How to define private constructors in javascript?

前端 未结 4 1208
旧巷少年郎
旧巷少年郎 2020-12-25 15:09

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

4条回答
  •  旧时难觅i
    2020-12-25 15:13

    One can use a variable (initializing) inside a closure which can throw an error if the constructor was called directly instead of via a class method:

    var Score = (function () {
      var initializing = false;
    
      var Score = function (score, hasPassed) {
          if (!initializing) {
             throw new Error('The constructor is private, please use mkNewScore.');
          }
    
          initializing = false;
          this.score = score;
          this.hasPassed = hasPassed;
      };
    
      Score.mkNewScore = function (score) {
          intializing = true;
          return new Score(score, score >= 33);
      };
    
      return Score;
    })();
    

提交回复
热议问题