我已经在JS中定义了纯对象,这些对象公开了某些静态方法,这些方法应用于构造它们而不是构造函数。如何在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;
})();
更新:解决方案应该仍然允许我测试x instanceof Score
。否则,@ user2864740的解决方案仅公开静态构造函数。
有没有可以让我说的解决方案
x instanceof Score
?
是的。从概念上讲,@ user2864740是正确的,但instanceof
要正常工作,我们需要公开(return
)函数而不是普通对象。如果该函数与.prototype
我们内部的私有构造函数相同,则instanceof
运算符将执行预期的操作:
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 (…)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句