Search code examples
javascriptoopsetterdefineproperty

Object create define property setter


I need to make it so that every time a specific property on my object is changed - it will call a special method on the same object.

Example:

MyObject.prototype = Object.create({
    specialMethod: function() { /* ... */ }
  }, {
    someValue: {
      set: function(value) {

        /* HOW DO I ASSIGN THE VALUE TO MyObject HERE?*/
        /* I can't do: this.someValue=value, that would create endless recursion */

        this.specialMethod();
      }
    }
  });

How do I assign the value to MyObject within the property setter?


Solution

  • There is no storage place in a getter/setter property, you cannot store values on it. You need to store it somewhere else and create a getter for that. Two solutions:

    1. Use a second, "hidden" property:

      MyObject.prototype.specialMethod: function() { /* ... */ };
      Object.defineProperty(MyObject.prototype, "someValue", {
          set: function(value) {
              this._someValue = value;
              this.specialMethod();
          },
          get: function() {
              return this._someValue;
          }
      });
      
    2. Use a closure variable (typically created on construction of the instance):

      function MyObject() {
          var value;
          Object.defineProperty(this, "someValue", {
              set: function(v) {
                  value = v;
                  this.specialMethod();
              },
              get: function() {
                  return value;
              }
          });
      }
      MyObject.prototype.specialMethod: function() { /* ... */ };