对于任何变量或属性,有没有办法知道它的值何时设置?
例如,说我有:
let x = { 'a': 1, 'b': 2 };
// x.a's set operation is linked to a method
x.a = 3; // the method is automatically called
当一个值改变时,有没有办法可以调用函数?很多代码都会改变这个值;我不想在整个地方添加方法调用。
我知道代理,但使用它们似乎需要一个单独的变量。意思是,x不能代表自己。
优选地,该技术将适用于原始和非原始。
x不能代表自己
当然可以。您只需执行操作即可将变量更改为指向代理
x = new Proxy(x, handler)
原始例子:
const handler = {
set: function(obj, prop, value) {
console.log('setting prop: ', prop, ' to ', value)
obj[prop] = value;
return true;
}
};
let x = { 'a': 1, 'b': 2 };
x = new Proxy(x, handler);
x.a = 3; // the method is automatically called
说实话,如果可以,请使用代理
如果你真的不能使用Proxy,你可以使用setter和getter来实现这一点
虽然它确实意味着重新声明你原来的x
对象,但我认为它被声明为内联,就像你问题中的Minimal,Complete和Verifiable示例
let x = {
_a: 1,
_b: 2,
get a() {
return this._a;
},
get b() {
return this._b;
},
set a(value) {
console.log(`changing a from ${this._a} to ${value}`);
this._a = value;
},
set b(value) {
console.log(`changing b from ${this._b} to ${value}`);
this._b = value;
}
};
x.a = 3;