My current focus is on TypeScript and I'm exploring the decorators functionality. I would greatly appreciate some guidance or expert knowledge on JavaScript capabilities in this area.
I am curious about dynamically adding a getter method to a Prototype object so that it can be executed instead of directly accessing a property on an instance.
Let's consider the following code:
class Car {
@decorate
color: string = 'red';
drive() {
return 'Driving';
}
}
function decorate(target, key) {
// It would be interesting to add a getter and update
// the target prototype to include such a getter
// I understand this specific implementation won't work, but it illustrates the concept.
target[key] = function() {
console.log(`Accessing property: ${key}`);
return eval(`this.${key}`)
}
}
When creating an object and trying to access .color
, for example:
const car = new Car();
car.color;
Ideally, the console output should be:
Accessing property: color