使用 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()
.
最佳答案
如果必须使用 getter 和 setter,一个相对简单的解决方案是将 x
和 y
也定义为 getter 和 setter。
get thing() {
var self = this;
return {
get x() {
return self._thing.x;
}
set x(value) {
self._thing.x = value;
}
// same for y
};
}
但您必须注意,每次访问 thing
进行读取时,都会创建一个新对象。尽管您可以通过缓存该对象并重用它来避免这种情况。
事实上,我可能根本不会有_thing
。我只需存储 _x
和 _y
并根据需要生成一个对象:
class Foo {
get thing() {
if (this._thing) {
return this._thing;
}
var self = this;
return this._thing = {
get x() {
return self._x;
}
set x(value) {
self._x = value;
}
};
}
set thing(value) {
this._x = value.x;
this._y = value.y;
}
}
关于javascript - ES6 : How to have a getter/setter for an object AND its properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43283974/