【发布时间】:2018-01-12 13:43:39
【问题描述】:
我正在尝试在名称空间(IIFE 模块模式)中创建一个构造函数,该构造函数具有只能通过 set/get 方法更改的 私有实例成员。 我使用返回 get/set 函数的 IIFE,该函数在数据上创建一个闭包,并将 get/set 返回给实例属性。 根据我的测试,该模式似乎有效;意味着成员是私有的,只能通过 get/set 访问。
A) 你认为这是真的吗?
B) 这些是好的模式还是有更好的替代方案(在 ES5 中)?
结构和小提琴:
IIFE module -> constructor-> IIFE that returns get/set
提前谢谢
//namespace
var computerModule = (function() {
//function constructor
function Computer(CPUMemory, diskMemory, CPUModel, price, warrantyInYears) {
this.CPUMemory = CPUMemory;
this.diskMemory = diskMemory;
this.CPUModel = CPUModel;
}
Computer.prototype.buyAccessories = buyAccessories;
Computer.prototype.print = print;
Computer.prototype.toString = toString;
function buyAccessories() {
}
function print() {
console.log(this.toString());
}
function toString() {
return `CPUMemory: ${this.CPUMemory},diskMemory: ${this.diskMemory}, CPUModel: ${this.CPUModel}, price: ${price}, warrantyInYears: ${warrantyInYears}`;
}
//return constructor
return {
Computer
}
})();
//namespace
var laptopComputerModule = (function() {
//constructor
function Laptop(CPUMemory, diskMemory, CPUModel, price, warrantyInYears, ChargingTime, ) {
computerModule.Computer.call(this, CPUMemory, diskMemory, CPUModel, price,
warrantyInYears);
//trying to create a member that cannot be directly changed - need feeback
Object.defineProperty(this, "BatteryChargingTime", {
value: (function() {
//private variable
var BatteryChargingTime;
//constructor init
BatteryChargingTime = ChargingTime;
function get() {
return BatteryChargingTime;
}
function set(arg) {
BatteryChargingTime = arg;
}
return { //functions create closuers on variables in this function, keeping its scope intact
get,
set
}
}()),
writable: false,
configurable: true
})
}
}());
【问题讨论】:
-
请在您的问题中包含代码。
-
问题:为什么让成员“绝对私密”如此重要,这是否证明了这种向后弯曲的合理性?
标签: javascript constructor private getter-setter ecmascript-5