gpt4 book ai didi

javascript - JS ES5 面向对象 : private instance member via get/set in constructor

转载 作者:行者123 更新时间:2023-12-01 02:32:22 24 4
gpt4 key购买 nike

我正在尝试在命名空间(IIFE 模块模式)中创建一个构造函数,该构造函数具有只能通过 set/get 方法更改的私有(private)实例成员。我使用返回 get/set 函数的 IIFE,这些函数在数据上创建闭包,并将 get/set 返回到实例属性。从我的测试来看,该模式似乎有效;这意味着成员是私有(private)的,只能通过 get/set 访问。

A)你认为这是真的吗?

B)这些模式是好的模式还是有更好的替代方案(在 ES5 中)?

结构和 fiddle :

IIFE module -> constructor-> IIFE that returns get/set

Fiddle

提前致谢

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

最佳答案

无需在构造函数中放置 IIFE。构造函数function已经提供了一个范围。

function Laptop(CPUMemory, diskMemory, CPUModel, price, warrantyInYears, ChargingTime, ) {
computerModule.Computer.call(this, CPUMemory, diskMemory, CPUModel, price, warrantyInYears);

this.BatteryChargingTime = {
get: function() {
return ChargingTime;
},
set: function(arg) {
ChargingTime = arg;
}
}
}

除此之外,这是一个完全标准的模式。 (当然,创建一个可以通过其 setter 方法任意设置的“私有(private)”成员是没有意义的)。

关于javascript - JS ES5 面向对象 : private instance member via get/set in constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48227519/

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