Decorator
by lvo811
Babel + JSX
/*
logAccess decorator will be executed for each annotated property within the code.
This enables us to intercept property definition of the given property.
Decorator (logAccess) functions that are placed on **class properties** (openSafe()) will
be called with the target object (MoneySafe) of the property definition as a first paramenter,
second parameter is the actual property name that is defined (openSafe)
last parameter is the descriptor object that is supposed to be applied to the object.
descriptor value which is the annotated function openSafe, it intercepts it with a
proxy function that will log the function openSafe before calling the origin function
*/
function logAccess(obj, prop, descriptor) {
const delegate = descriptor.value;
descriptor.value = function(){
console.log(`${prop} was called!`);
return delegate.apply(this, arguments);
}
}
class MoneySafe {
@logAccess openSafe() {
this.open = true;
console.log('safe is opened');
}
}
const safe = new MoneySafe();
safe.openSafe();