对于嵌套对象,使用父对象中的方法为键赋值的最佳实践是什么?[复制]

Regarding nested objects, what is the best practice for assigning a value to a key using a method that is in the parent object? [duplicate]

提问人:Garland 提问时间:8/8/2022 更新时间:8/11/2022 访问量:45

问:

使用父对象中的方法为键赋值的最佳做法是什么?

我尝试了以下几种变体:

const data = {
  one : {
    a : {
      hours : 100,
      minutes : getMinutes()
    },
    b : {
      hours : 24,
      minutes : getMinutes()
    }
  },
  getMinutes : function() {
    return this.hours * 60
  }
}
JavaScript 方法 这个 嵌套对象

评论

2赞 VLAZ 8/8/2022
相关:对象文字/初始值设定项中的自引用
0赞 Bergi 8/11/2022
定义然后使用function time(hours) { return {hours, minutes: hours*60}; }const data = {one: {a: time(24), b: time(100)}};

答:

0赞 Garland 8/11/2022 #1

这并不是对象的真正预期目的。最佳做法是创建一个外部函数来获取值。

例:

const getMinutes = (hours) => {
    return hours * 60
  }
}
const data = {
  one : {
    a : {
      hours : 100,
      minutes : getMinutes(100)
    },
    b : {
      hours : 24,
      minutes : getMinutes(24)
    }
  }
}