Questions
11.1. Decorating methods, the future way. In Chapter 6, Producing Functions - Higher-Order Functions, we wrote a decorator to enable logging for any function. Currently, method decorators are being considered for upcoming versions of JavaScript: refer tohttps://tc39.github.io/proposal-decorators/ for that (Draft 2 means that inclusion of this feature in the standard is likely, although there may be some additions or small changes). Study the draft and take a look at what makes the next code tick.
Some questions: Do you see the need for the savedMethod
variable? Why do we use function()
when assigningnew descriptor.value
, instead of an arrow function? Can you understand why .bind()
is used? What is descriptor
?
const logging = (target, name, descriptor) => {
const savedMethod = descriptor.value;
descriptor.value = function(...args) {
console.log(`entering ${name}: ${args}`);
try {
const valueToReturn = savedMethod.bind(this)(...args);
...