One advice we usually hear as developers is to do our very best to not repeat code. So what we do is place code which could be used numerous time in its separate function. But sometimes, it isn't so simple. Take try catch blocks for example,
try {
console.log("loading...")
// run some code
console.log("Finished.")
} catch (error) {
console.log(error)
}
JavaScript does have allocation for decorators. But there are only available for class methods and class fields. You can read more here.
But for now, we will be taking a look at a function decorators. A way to have a decorators for functions outside a class is to use higher function. This is a function that returns a function. This could be designed like a function wrapper
Say you have a function
function printText(text){
Code says, ${text}
console.log();
}
And you want to wrap this function code with the try catch block from above.
function loggingDecorator(wrappedFn) {
return function() {
try {
console.log("loading...")
// run some code
console.log("Finished.")
} catch (error) {
console.log(error)
}
}
}
You use the decorator like this
const wrapped = loggingDecorator(printText);
wrapped("have a good day.");
Thanks for reading.
Top comments (3)
Typo: should say "... not to repeat code."
Thanks
Sir, You might find wrapping your source code examples in
'''JavaScript
''' where apostrophise are back-ticks.
For example: