Home > Article > Web Front-end > There are several types of decorators in es6
There are two types of es6 decorators. Decorators can only be used for classes and class methods, so they can be divided into: 1. Class decorators, used to decorate the entire class, the syntax is "@ function name"; 2. Class method decorators, used to decorate methods of the class , the syntax is "@ function name method name".
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
There are two types of es6 decorators.
Decorator (Decorator) is a syntax related to a class (class), used to annotate or modify class-related methods and properties. Many object-oriented languages have this feature. Generally related to classes, don't use ordinary methods.
Decorator is a function, written as @ function name. It can be placed before the definition of classes and class methods. The decorator is to execute the function and add some control conditions to the class or the attribute methods under the class.
Decorators can only be used for classes and class methods, and cannot be used for functions because of function promotion.
1. Class decorator
Class decorator is used to decorate the entire class
The example is as follows:
@decorateClass class Example { //... } function decorateClass(target) { target.isTestClass = true }
As in the above code , the decorator @decorateClass modifies the behavior of the entire Example class and adds a static attribute isTestClass to the Example class. A decorator is a function. The parameter target in the decorateClass function is the Example class itself, which is also equivalent to the class constructor Example.prototype.constructor.
2. Class method decorator
Class method decorators are used to decorate class methods
Examples are as follows:
class Example { @log instanceMethod() { } @log static staticMethod() { } } function log(target, methodName, descriptor) { const oldValue = descriptor.value; descriptor.value = function() { console.log(`Calling ${name} with`, arguments); return oldValue.apply(this, arguments); }; return descriptor; }
As in the above code, the decorator @log decorates the instance method instanceMethod and the static method staticMethod respectively. The function of the @log decorator is to execute console.log to output the log before performing the original operation.
【Related recommendations: javascript video tutorial, web front-end】
The above is the detailed content of There are several types of decorators in es6. For more information, please follow other related articles on the PHP Chinese website!