How to define private constructors in javascript?

前端 未结 4 1219
旧巷少年郎
旧巷少年郎 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:30

    Is there a solution which will allow me to say x instanceof Score?

    Yes. Conceptually, @user2864740 is right, but for instanceof to work we need to expose (return) a function instead of a plain object. If that function has the same .prototype as our internal, private constructor, the instanceof operator does what is expected:

    var Score  = (function () {
    
      // the module API
      function PublicScore() {
        throw new Error('The constructor is private, please use Score.makeNewScore.');
      }
    
      // The private constructor
      var Score = function (score, hasPassed) {
          this.score = score;
          this.hasPassed = hasPassed;
      };
    
      // Now use either
      Score.prototype = PublicScore.prototype; // to make .constructor == PublicScore,
      PublicScore.prototype = Score.prototype; // to leak the hidden constructor
      PublicScore.prototype = Score.prototype = {…} // to inherit .constructor == Object, or
      PublicScore.prototype = Score.prototype = {constructor:null,…} // for total confusion :-)
    
      // The preferred smart constructor
      PublicScore.mkNewScore = function (score) {
          return new Score(score, score >= 33);
      };
    
      return PublicScore;
    }());
    

    > Score.mkNewScore(50) instanceof Score
    true
    > new Score
    Error (…)
    

提交回复
热议问题