Object create define property setter

◇◆丶佛笑我妖孽 提交于 2019-12-12 02:51:49

问题


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?


回答1:


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() { /* ... */ };
    


来源:https://stackoverflow.com/questions/25998325/object-create-define-property-setter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!