对象defineProperty属性的setter

时间:2014-10-25 23:50:56

标签: javascript node.js

使用NodeJS,我试图跟踪Model属性的变化,无论它们是什么类型。使用Object.defineProperty setter通常效果很好,但对于Objects和数组,如果设置了对象的属性,我将无法跟踪所做的更改。

我意识到setter本身并不是对象,但有没有办法让它像它一样运行?

例如,如果设置了setter的“property”,我可以获得以下代码来触发setter吗?

var model = {};
model.attributes = {};

Object.defineProperty(model, 'options', {
    get: function() {
        return this.attributes.options;
    },
    set: function(value) {
        console.log('changed options from:', this.attributes.options, 'to', value);
        this.attributes.options = value;
    }
});

model.options = {};
model.options = { a: 50 }; // triggers setter
model.options.b = 60;      // doesn't trigger setter, how can I get it to do so?

1 个答案:

答案 0 :(得分:4)

如果您正在使用支持代理的ES6转换器,您可以像这样解决问题:

var handler = {
  defineProperty (target, key, descriptor) {
    console.log('changed options from:', target[key], 'to', descriptor.value);
    if(typeof descriptor.value === 'object'){
        descriptor.value = new Proxy(descriptor.value,handler);
    }
    Object.defineProperty(target, key, descriptor);
    return true;
  }
}

var target = {}
var proxy = new Proxy(target, handler)

proxy.foo = 'bar2'        // changed from undefined to bar2
proxy.foo = 'bar'         // changed from bar2 to bar
proxy.options = { a: 50 } // changed from undefined to Object { a: 50 }
proxy.options.a = 15      // changed from 50 to 15
proxy.options.b = 60      // changed from undefined to 60

this文章启发