javascript - ES6 : How to have a getter/setter for an object AND its properties

标签 javascript ecmascript-6

使用 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.xthing.y 应始终使用 Math.round().

最佳答案

如果必须使用 getter 和 setter,一个相对简单的解决方案是将 xy 也定义为 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/

相关文章:

javascript - 如何在类构造函数中添加限制?

javascript - 一个非空的整数列表

javascript - 对象数组在条件匹配时返回对象

javascript - 如何在 sequelize 上使用实例方法

javascript - 过滤箭头函数 (ES6)

javascript - 使用 setState 设置新状态和更改旧状态之间的区别

javascript - Number.prototype.toLocaleString() 和 Intl.NumberFormat.prototype.format 之间有什么关系?

javascript - JavaScript 变量可以输入吗?

javascript - ionic 3 : How can i get variable inside observable

javascript - 根据对象数组过滤对象数组返回相同的结果