I need some guidance or expert knowledge on JavaScript capabilities. I'm studying TypeScript ATM, specifically decorators functionality.
Is there a way to dynamically add a getter method to a Prototype object so that it is executed in place of the plain property access on an instance.
Here's some code for example:
class Car {
@decorate
color: string = 'red';
drive(): {
return 'Driving';
}
}
function decorate(target, key): void {
//would be cool to add a getter and update
//the prototype in target to contain such getter
//I know this won't work, but to get the idea.
target[key] = get function() {
console.log(`Accessing property: ${key}`);
return eval(`this.${key}`)
}
}
Then, when I would create and object and try to access .color
const car = new Car();
car.color;
ideally I would see at the console
Accessing property: color