Is it possible, given the following object
let target = {
foo:0,
result:[],
bar(){
//some code
}
}
to then wrap said object in a Proxy()
let handler = {
get(){
// code here
},
apply(){
// code here
}
}
target = new Proxy(target,handler);
that catch the call to bar()
and save the result to results:[]
?
I've given it a few tries
let target = {
called:0,
results:[],
foo(bar){
return bar;
},
}
let handler = {
get(target,prop){
console.log('Get Ran')
return target[prop];
},
apply(target,thisArg,args){
console.log('Apply Ran')
// never runs
}
}
target = new Proxy(target,handler);
target.foo();
This code misses [[ apply ]] but catches the [[ get ]] (if memory serves, object method calls are done as two operations , [[ get ]] [[ apply ]])
let target = {
called:0,
results:[],
foo(bar){
return bar;
},
}
let handler = {
get(target,prop){
return target[prop];
},
apply(target,thisArg,args){
let product = target.apply(thisArg,args)
return product;
},
}
let prox = new Proxy(target.foo,handler);
console.log(prox('hello'));
If I instead wrap the object method in a proxy it catches the [[ apply ]] but I lose the reference to the original object ( this ) and therefore lose access to the result array
I've also tried nesting the method proxy inside of the object proxy.
any thoughts ?
// Documentation for Proxy
// Other questions , about proxy , but not this use case