提问人:Garland 提问时间:8/8/2022 更新时间:8/11/2022 访问量:45
对于嵌套对象,使用父对象中的方法为键赋值的最佳实践是什么?[复制]
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]
问:
使用父对象中的方法为键赋值的最佳做法是什么?
我尝试了以下几种变体:
const data = {
one : {
a : {
hours : 100,
minutes : getMinutes()
},
b : {
hours : 24,
minutes : getMinutes()
}
},
getMinutes : function() {
return this.hours * 60
}
}
答:
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)
}
}
}
评论
function time(hours) { return {hours, minutes: hours*60}; }
const data = {one: {a: time(24), b: time(100)}};