gpt4 book ai didi

javascript - 如何在javascript中定义私有(private)构造函数?

转载 作者:可可西里 更新时间:2023-11-01 01:49:59 26 4
gpt4 key购买 nike

我在 JS 中定义了纯对象,它公开了某些应该用于构造它们而不是构造函数的静态方法。如何在 Javascript 中为我的类创建一个私有(private)的构造函数?

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 仅公开静态构造函数的解决方案有效。

最佳答案

可以在闭包内使用变量(initializing),如果直接调用构造函数而不是通过类方法调用,则可能会抛出错误:

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;
})();

关于javascript - 如何在javascript中定义私有(private)构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21667149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com