[英]Javascript Proxy, howto trigger trap from inside of your target
When creating a proxy in javascript like this 在像这样的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();
the set "trap" will never be called I have no problem understanding why this happens, but how should one solve such a situation? 我永远不会毫无疑问地理解为什么会发生这种情况,但是应该如何解决这种情况呢?
One solution would be to expose the self variale to the outside, and let "someone" change it to the proxy, not very obviouse for anyone using the t object.... 一种解决方案是将自变量向外部公开,然后让“某人”将其更改为代理,对于使用t对象的任何人来说都不是很明显。
Is there any other way? 还有其他办法吗? Am I misusing the proxy?
我滥用代理吗?
The solution would be not to use self
at all: 解决方案是根本不使用
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();
If someFunc
does not use the proxy, you cannot force it to without rewriting your T
. 如果
someFunc
不使用代理,则不能在不重写T
情况下强制使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.