Javascript代理,如何从目标内部触发陷阱

时间:2017-06-12 13:15:13

标签: javascript proxy

在像这样的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对象的任何人来说都不是非常明显....

还有其他方法吗? 我是否滥用代理?

1 个答案:

答案 0 :(得分:0)

解决方案是根本不使用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的情况下强制使用代理。