2

我需要这样做,以便每次更改我的对象上的特定属性时 - 它都会在同一个对象上调用一个特殊方法。

例子:

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();
      }
    }
  });

如何在属性设置器中将值分配给 MyObject?

4

1 回答 1

6

getter/setter 属性中没有存储位置,您不能在其上存储值。您需要将其存储在其他地方并为此创建一个吸气剂。两种解决方案:

  1. 使用第二个“隐藏”属性:

    MyObject.prototype.specialMethod: function() { /* ... */ };
    Object.defineProperty(MyObject.prototype, "someValue", {
        set: function(value) {
            this._someValue = value;
            this.specialMethod();
        },
        get: function() {
            return this._someValue;
        }
    });
    
  2. 使用闭包变量(通常在构造实例时创建):

    function MyObject() {
        var value;
        Object.defineProperty(this, "someValue", {
            set: function(v) {
                value = v;
                this.specialMethod();
            },
            get: function() {
                return value;
            }
        });
    }
    MyObject.prototype.specialMethod: function() { /* ... */ };
    
于 2014-09-23T15:08:56.530 回答