You can achieve this with getters and setters.
var obj = {
get foo() {
console.log({ name: 'foo', object: obj, type: 'get' });
return obj._foo;
},
set bar(val) {
console.log({ name: 'bar', object: obj, type: 'set', oldValue: obj._bar });
return obj._bar = val;
}
};
obj.bar = 2;
// {name: 'bar', object: <obj>, type: 'set', oldValue: undefined}
obj.foo;
// {name: 'foo', object: <obj>, type: 'get'}
Alternatively, in a browser with support for Proxies, you can write a more generic solution.
var obj = {
foo: 1,
bar: 2
};
var proxied = new Proxy(obj, {
get: function(target, prop) {
console.log({ type: 'get', target, prop });
return Reflect.get(target, prop);
},
set: function(target, prop, value) {
console.log({ type: 'set', target, prop, value });
return Reflect.set(target, prop, value);
}
});
proxied.bar = 2;
// {type: 'set', target: <obj>, prop: 'bar', value: 2}
proxied.foo;
// {type: 'get', target: <obj>, prop: 'bar'}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…