I have implemented a proxy to track all property access on instances of a class, demonstrated in the code snippet below:
class Person {
public ageNow: number;
public constructor(ageNow: number) {
this.ageNow = ageNow;
const proxy = new Proxy(this, {
get: (target, property) => {
console.log(property);
return target[property as keyof typeof target];
},
});
return proxy;
}
public ageIn10Years1() {return this.ageNow + 10;}
public get ageIn10Years2() {return this.ageNow + 10;}
}
When I create an instance and call a method like:
const peter = new Person(18);
console.log(peter.ageIn10Years1());
it logs 'ageInYears1'
, 'ageNow'
, and 28
(in that order), which aligns with my expectations.
However, when I use a getter like:
console.log(peter.ageIn10Years2);
which also prints 'ageInYears2'
and 28
but not 'ageNow'
, even though this property is being accessed.
What could be causing this behavior and how can it be resolved?