【问题标题】:JS ES5 OOP: private instance member via get/set in constructorJS ES5 OOP:私有实例成员通过构造函数中的 get/set
【发布时间】: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

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

【问题讨论】:

  • 请在您的问题中包含代码。
  • 问题:为什么让成员“绝对私密”如此重要,这是否证明了这种向后弯曲的合理性?

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


【解决方案1】:

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

【讨论】:

  • 你能解释一下闭包以及它与实例的关系吗? get 函数在构造函数上的变量上“关闭”,保持其范围。执行关闭的函数存在于实例上的对象上?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-02
  • 2012-08-21
  • 1970-01-01
  • 2013-03-27
  • 1970-01-01
  • 2019-01-24
  • 1970-01-01
相关资源
最近更新 更多