繁体   English   中英

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

[英]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]

使用父 object 中的方法为键分配值的最佳实践是什么?

我尝试了以下几种变体:

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

这并不是对象的真正预期目的。 最佳实践是创建一个外部 function 来获取值。

例子:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM