ES7 Decorators for People in a Hurry

MGT
2 min readJan 4, 2021

Decorators are somewhat comparable to annotations, as known from languages such as Java. The following article shows how they can be used.

The principle of the Decorators

The principle of the Decorators can be summarized relatively simply: Similar to the annotation syntax, Decorators are used to mark up certain methods of a class or the class itself. If the class is initialized then, the accordingly set Decorator is called before. This is ultimately a simple function with three parameters: the object on which the method is defined (target), the name of the method (name) and the property descriptor (descriptor), i.e. the object that contains various property attributes.

The following listing shows a simple example. At the top you can see the definition of the decorator, which is a simple function with three parameters. The print() method of the Printer class is then tagged with the decorator via @decoratorFunction, which ensures that the decoratorFunction() function is called before the Printer class itself is initialized.

function decoratorFunction(target, name, descriptor) {
console.log(target); // Printer {}
console.log(name); // print
console.log(descriptor); // Object {value: function,
enumerable: false, configurable: true, writable: true}
}

class Printer{
@decoratorFunction
print(str) {
console.log(str)
}
}

const printer = new Printer();
const result = printer.print("Hey");
console.log(result);

Optionally, a decorator function can return a property descriptor. For example, the following example shows a decorator function that prevents a method from being redefined by setting the writable property of the property descriptor to false.

function readonly(target, name, descriptor) {
descriptor.writable = false;
}

class Account{
constructor(name, password) {
this.name = name;
this.password = password;
}
@readonly
toString() {
return '[Name: ' + this.name + ']';
}
}

const account = new Account('John Doe', '********');
console.log(user.toString());
// Uncaught TypeError: Cannot assign to read only property 'toString' of [object Object]'
Account.prototype.toString = function() {
return '[Name: ' + this.name + ', Pass: ' + this.password + ']';
}

If you use a decorator function on a class, you only have access to the target object within the function, which in this case is the corresponding constructor:

@component
class Account { }

function component(target, name, descriptor) {
console.log(target); // function Account() {...}
console.log(name); // undefined
console.log(descriptor); // undefined
target.isComponent = true;
}
console.log(Account.isComponent); // true

Summary

Decorators increase the reusability of the source code and provide an easy way to add additional information to classes and methods and to influence the property descriptor.

--

--