JS ES5 OOP:私有实例成员通过构造函数中的get / set

时间:2018-01-12 13:43:40

标签: javascript constructor private getter-setter ecmascript-5

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

A)你认为这是真的吗?

B)这些好的模式还是有更好的选择(在ES5中)?

结构和小提琴:

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

1 个答案:

答案 0 :(得分:2)

没有必要在构造函数中放置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方法任意设置的“私人”成员是没有意义的。)