javascript - 构造函数中的复合属性

标签 javascript

我想构建一个如下所示的对象数组:

var someObject = {
  id,
  groupA {
    propertyA: 0,
    propertyB: 0,
  },
  groupB {
    propertyA: 0,
    propertyB: 0
  totals {}
 }

并添加以下复合属性:

Object.defineProperty(someObject.groupA, "propertyC", 
  {
    get: function() { 
      return someObject.groupA.propertyA + someObject.groupA.propertyB;
    }
  });

并使用相同的方法添加属性:

  • groupB.propertyC -> groupB.propertyA + groupB.propertyB
  • totals.propertyA -> groupA.propertyA + groupB.propertyA
  • totals.propertyB -> groupA.propertyB + groupB.propertyB
  • totals.propertyC -> groupA.propertyC + groupB.propertyC

我通过将所有这些代码放入一个函数中来完成所有这些工作,因此它将 someObject 添加到数组中。

但后来我开始思考,不需要为每个对象创建只读复合属性,并且可能位于原型(prototype)中。

这有道理吗?这可能吗?如果可能的话:如何实现?

最佳答案

这是可以做到的。您只需确保 groupA 和 groupB 继承自具有 Composite 属性的对象即可。

var proto = {};
Object.defineProperty(proto, 'propertyC', {
  get : function() { return this.propertyA + this.propertyB; }
});

var someObj = {
  id : '1',
  groupA : Object.create(proto, {
    propertyA : { value : 1 }, propertyB : { value : 2 }
  }),
  groupB : Object.create(proto, {
    propertyA : { value : 3 }, propertyB : { value : 4 }
  }),
  totals : Object.create(proto, {
    propertyA : { get : function() { return someObj.groupA.propertyA + someObj.groupB.propertyA; } },
    propertyB : { get : function() { return someObj.groupA.propertyB + someObj.groupB.propertyB; } }
  })
}

// Usage: 
console.log(someObj.groupA.propertyC); // 3
console.log(someObj.groupB.propertyC); // 7
console.log(someObj.totals.propertyC); // 10

关于javascript - 构造函数中的复合属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21710732/

相关文章:

javascript - 如何连接到 HighCharts 中两个链接系列的端点

javascript - 使用固定参数的自定义顺序来 Currying Javascript 函数

javascript - Meteor - 如何从其他 JS 文件调用外部类方法?

javascript - 设置 Cookie 路径

javascript - 在 js 中从 Google Maps API 编辑针点描述标签

php - Joomla + Mootools XMLHttpRequest 问题

javascript - AngularJS - 使用结果从 Factory 读取 JSON

javascript - CKEDITOR.replace( 'editor1' , 'editor2' , {

javascript - 纯JS和html跨域ajax到外域

javascript - 使用数组元素替换多次出现的字符串