Proxy有一个new
运算符的陷阱,理论上它应该允许我们创建将构造函数参数传递到目标对象的Proxy。它的工作原理示例如下:
function monster1(disposition) {
this.disposition = disposition;
}
const handler1 = {
construct(target, args) {
console.log('monster1 constructor called');
// expected output: "monster1 constructor called"
return new target(...args);
},
get(...args) {
console.info('get trap triggered!')
}
};
const proxy1 = new Proxy(monster1, handler1);
const instance = new proxy1('fierce')
console.log(instance.disposition);
// expected output: "fierce"
console.log(instance.unknownProp);
// expected output: "get trap triggered!" <-- doesn't happen
这非常有效。除了CCD_ 2现在不再触发CCD_ 3陷阱。现在如何拦截属性?
在Construct
内部有return new target(...args);
。这创建了一个新的JS对象,没有设置任何代理。
您应该在新创建的对象上设置一个额外的代理,以拦截对该对象的属性访问。
像这样:
function monster1(disposition) {
this.disposition = disposition;
}
const handler1 = {
construct(target, args) {
console.log('monster1 constructor called');
// expected output: "monster1 constructor called"
const obj = new target(...args);
// Return a Proxy instead of object.
// We may use the same handler1 here, or we can
// create another handler with `get`. Both work,.
return new Proxy(obj, handler1);
},
get(...args) {
console.log('get trap triggered!')
return Reflect.get(...args);
}
};
const proxy1 = new Proxy(monster1, handler1);
const instance = new proxy1('fierce')
console.log(instance.disposition);
// expected output: "get trap triggered!"
// expected output: "fierce"
console.log(instance.unknownProp);
// expected output: "get trap triggered!"
我还没有试过,但我认为super
是你的答案。https://www.w3schools.com/jsref/jsref_class_super.asp