![]() |
VOOZH | about |
Decorators in JavaScript are a design pattern that enhances an object's behaviour by wrapping it with additional functionality, without altering its original code. It enable modifications like logging or security checks without changing the underlying implementation. It adopted from languages like Python and C#, allows for flexible extension of object functionality in JavaScript applications.
A decorator is a higher-order function that modifies the behaviour of a function, method, or class. Decorators are used for extending the functionality of a function, method, or class without modifying its code.
Syntax
// Define a decorator function that adds a static property to a class
let variable = function(object) {
object.property = 'characteristic';
};
// Apply the decorator to the class
@variable
class GFG {}
// Access the added property
console.log(GFG.property);
Example: It is an example of decorators in older JavaScript versions. The `add` function accepts `print` as a parameter, where `print` acts as a decorator appending "is best" to the string "GFG". By using `add`, we extend and invoke `print`, effectively concatenating the strings.
Output
GFG is BestTo run the decorators in JavaScript, we need to configure babel in out projec. Below is a step-by-step guide
Step 1: Initialize a Node App
npm initStep 2: Install Babel and Required Plugins
npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/plugin-proposal-decoratorsThe updated dependencies after installing above pacakges are:
"devDependencies": {
"@babel/cli": "^7.25.7",
"@babel/core": "^7.25.8",
"@babel/plugin-proposal-decorators": "^7.25.7",
"@babel/preset-env": "^7.25.8"
}
Step 3: Configure .babelrc file
// Filename - .babelrc
{
"plugins": [
["@babel/plugin-proposal-decorators", { "version": "legacy" }]
],
"presets": ["@babel/preset-env"]
}
Step 4: Define Decorator in index.js file
// Filename - index.js
let variable = function (target) {
target.property = 'GFG is best';
}
// Decorator
@variable
class GFG { }
// Print in the console
console.log(GFG.property);
Step 5: Compile the code using Babel
npx babel index.js --out-file compiled_output.jsThis command will output the compiled file which will look like this:
GFG is best
Step 6: Run the output file
node compiled_output.jsThe below example illustrates the decorators in JavaScript:
Example 1: Defining a decorator variable that adds a property to the class GFG, which is then accessed to log "GFG is best" in the console.
Output
GFG is bestExample 2: Defining a decorator factory variable that sets a class property based on the passed argument, assigning "GFG is Green" to GFG.property and logging it.
Output
GFG is GreenDecorators are called by the appropriate details of the item which will be decorated. Decorators are actually functions that return another function. There are two types of decorators are supported now:
These decorators are applied to a single member of a class. This decorator has properties, methods, getters, and setters. This decorator accepts 3 parameters:
Example 1: This example defines a method decorator gfg that logs the parameters and result of the add method in the geek class.
Output
parameters: 100, 200
addition: 300
Example 2: This example demonstrates a readonly decorator to make the getColor method of the car class non-writable, preventing it from being overridden.
Output
car is BlackThese decorators are applied to the entire class. These functions are called with a single parameter which is to be decorated. This function is a constructor function. These decorators are not applied to each instance of the class, it only applies to the constructor function. These decorators are less useful than class member decorators. Because we can use a simple function to do everything which can be done by these decorators.
Example: This example demonstrates using a log decorator to log the parameters passed to the gfg class constructor.
Output
(...args) =>
{
console.log(`Parameters : args`);
return new Class(...args);
}