【发布时间】:2017-04-08 03:22:16
【问题描述】:
使用 JS getter 和 setter,我的目标是创建以下 API 案例:
// the user should be able to write this to update thing
thing = {
x: 1,
y: 2
}
// OR they should be able to write this
thing.x = 1
thing.y = 2
现在我正在使用这样的代码:
get thing() {
return {
x: this._thing.x,
y: this._thing.y
};
}
set thing(value) {
this._thing.x = value.x,
this._thing.y = value.y
}
这支持第一种情况,但不支持第二种情况。
这可以通过任何相当简单的方式完成吗?
编辑:我将输入一个示例,但一个用例可能是 thing.x 和 thing.y 应该始终使用 Math.round() 舍入为整数。
【问题讨论】:
-
thing返回一个新对象。 -
是的,这是课程的一部分。还是你建议我把 _thing 变成一个类实例?因为,在我的项目中,它实际上已经是......
-
为什么要有getter和setter呢?除非您没有提及特定原因,否则不使用它们会免费提供您想要的东西。
-
为了清楚起见,我用代码缩短了问题。请相信我,我在这里需要 getter 和 setter。我会尝试发布一个更完整的代码示例。