Search⌘ K
AI Features

Using Decorators

Learn how decorators in JavaScript provide a way to inject metadata and additional behavior into classes and functions, similar to annotations in other languages. This lesson covers the purpose, usage, and implementation of decorators, including examples inspired by Angular components, to help you understand how to extend functionality in modern JavaScript development.

Why decorators?

The Proxy class you have seen so far in this chapter is very useful to synthesize or cook up your own dynamic methods and properties into existing classes. However, sometimes you want to bring a recipe of methods that someone else has created into your own classes and functions. In other words, you want to alter your classes or functions with metadata that, for example, a library or framework expects to find. This is where decorators come in.

Decorators in JS

JavaScript decorators serve a similar purpose as annotations in Java and attributes in C#.

Decorators: Decorators offer a way to extend the capabilities of the subject that they decorate or annotate.

Let’s take a quick look at an example function declaration from Async and Await.

const callCompute = async function(number) {

To convey that a function may be making asynchronous calls, JavaScript offers the async keyword to decorate the code. Nice decoration, but it came as a keyword in the language. We, as users of the language, can’t add keywords or ...