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


using js getters , setters, aiming create following api case:

// user should able write update thing  thing = {    x: 1,    y: 2 }  // or should able write  thing.x = 1 thing.y = 2 

right using code this:

 thing() {    return {      x: this._thing.x,      y: this._thing.y    };  }   set thing(value) {    this._thing.x = value.x,    this._thing.y = value.y  } 

this supports first case, not second case.

can done in reasonably simple way?

edit: type example, use case might thing.x , thing.y should round integer using math.round().

if have use getters , setters, relatively simple solution define x , y getters , setters well.

get thing() {   var self = this;   return {     x() {       return self._thing.x;     }     set x(value) {       self._thing.x = value;     }     // same y   }; } 

but have aware every time thing accessed reading, new object created. though avoid caching object , reuse it.

in fact, wouldn't have _thing @ all. i'd store _x , _y , generate object once on demand:

class foo {   thing() {     if (this._thing) {       return this._thing;     }      var self = this;     return this._thing = {       x() {         return self._x;       }        set x(value) {         self._x = value;       }     };   }    set thing(value) {     this._x = value.x;     this._y = value.y;   } } 

Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -