在javascript中创建代理时
var t = function() {
self = this;
this.a = "abc";
someFunc: function () {
self.a = "def";
}
}
target = new t();
var p = New Proxy(target, {
set: function(){
//this will never be called when the someFunc changes the a field.
}
})
p.someFunc();
设定的"陷阱"永远不会被称为 我没有问题理解为什么会发生这种情况,但是应该如何解决这种情况?
一种解决方案是将自我变量暴露在外部,并让"某人"将其更改为代理,对于使用 t 对象的任何人来说都不是很明显......
还有其他办法吗?我是否滥用了代理?
解决方案是根本不使用self
:
function T() {
this.a = "abc";
this.someFunc = function () {
this.a = "def"; // `this` in the method (usually) refers to the proxy
};
}
var p = new Proxy(new T, {
set: function(target, key, value, receiver) {
console.log(key, value);
return Reflect.set(target, key, value, receiver);
}
});
p.someFunc();
如果someFunc
不使用代理,则无法在不重写T
的情况下强制它。