[英]Javascript proxy for nested object (apply for all function calls)
I'm looking for away to use a proxy on a nested object. In this example I would like to add 1 in my proxy for the result of every function call in that object. How would I go about this, since I can't use apply on the testobj directly.我正在寻找在嵌套的 object 上使用代理。在这个例子中,我想在我的代理中为 object 中每个 function 调用的结果添加 1。我将如何处理 go,因为我不能直接在 testobj 上使用 apply 。 Thanks for any input.
感谢您的任何输入。
const testObj = {
add: (a: number, b: number) => a + b,
subtract: (a: number, b: number) => a - b,
multiply: (a: number, b: number) => a * b,
...
}
const proxy = new Proxy(testObj, {
// for the result of every function call (add / subtract ....)
// i would like to add 1 to the result
})
In the end I found the way to do.最后我找到了方法。 It was to return another proxy from the get trap.
它是从 get 陷阱返回另一个代理。 Just posting this in case anyone stumbles across the same problem.
只是张贴这个以防万一有人遇到同样的问题。
const testProxy = new Proxy(testObj, {
get: (
target: typeof testObj,
key: keyof typeof testObj,
): any => {
if (typeof target[key] !== 'function') {
return target[key]
} else {
return new Proxy(target[key], {
apply: (
target: any,
thisArg: any,
argArray?: any[],
): any => {
console.log('triggered')
return target(...argArray) + 1
},
})
}
},
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.