Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the decorator in es6

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to realize the decorator in es6". In the daily operation, I believe that many people have doubts about how to realize the decorator in es6. The editor consulted all kinds of materials and sorted out a simple and easy-to-use method of operation. I hope it will be helpful to answer the doubt of "how to realize the decorator in es6". Next, please follow the editor to study!

In es6, a Decorator is a class-related syntax used to annotate or modify classes and class methods; a decorator is actually a function executed at compile time, with the syntax "@ function name", usually before the definition of classes and class methods. There are two kinds of decorators: class decorator and class method decorator.

The operating environment of this tutorial: windows7 system, ECMAScript version 6, Dell G3 computer.

The decorator pattern (Decorator Pattern) allows you to add new functionality to an existing object without changing its structure. This type of design pattern is a structural pattern, which is a wrapper of an existing class.

This pattern creates a decoration class that wraps the original class and provides additional functionality while maintaining the integrity of the class method signature.

ES6 decorator

In ES6, a Decorator is a class-related syntax used to annotate or modify classes and class methods.

A decorator is actually a function, usually in front of classes and class methods.

The decorator changes the behavior of the class at compile time, not at run time; the decorator is essentially a function executed at compile time

The decorator can be used to decorate the entire class

@ decorateClassclass Example {@ decorateMethods method () {}}

Two decorators are used in the above code, the @ decorateClass () decorator is used in the class itself to add or modify the class's functionality, and the @ decorateMethods () decorator is used in the class's methods to annotate or modify class methods.

Two types of decorators

Decorators can only be used for classes and class methods, not for functions, because there is a function promotion.

Decorators can only be used for classes and class methods. Let's take a look at the use of the two types of decorators.

1. Class decorator

Class decorator is used to decorate the entire class

Parameters of class decorator

Target: the class itself, which is equivalent to the constructor of the class: Class.prototype.constructor.

@ decorateClassclass Example {/ /...} function decorateClass (target) {target.isTestClass = true}

As in the code above, the decorator @ decorateClass modifies the behavior of the entire Example class, adding the static attribute isTestClass to the Example class. The decorator is a function, and the parameter target in the decorateClass function is the Example class itself, which is also equivalent to the constructor Example.prototype.constructor of the class.

Decorator transmits parameters

The decorator implemented above cannot pass parameters when in use. If you want to pass in parameters in the use of the decorator, you can encapsulate another layer of function outside the decorator.

@ decorateClass (true) class Example {/ /...} function decorateClass (isTestClass) {return function (target) {target.isTestClass = isTestClass}}

The decorator implemented in the above code can be used to pass parameters so that the behavior of the decorator can be modified according to different scenarios.

In actual development, when React is used in conjunction with the Redux library, it is often written as follows.

Class MyReactComponent extends React.Component {} export default connect (mapStateToProps, mapDispatchToProps) (MyReactComponent)

With the decorator, you can rewrite the above code.

@ connect (mapStateToProps, mapDispatchToProps) export default class MyReactComponent extends React.Component {}

2. Class method decorator

A method used by a class method decorator to decorate a class.

Parameters of class method decorator

Target:

The class method decorated by the decorator is static: target is the constructor of the class

The class method decorated by the decorator is the instance method: target is the prototype object of the class

Method: the name of the decorated class method

Descriptor: attribute descriptor of the decorated member

/ / the original values of the descriptor object are as follows: {value: specifiedFunction, enumerable: false, configurable: true, writable: true}; 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 code above, 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 logs before performing the original operation.

Class method decorator passes parameters

The decorator implemented above cannot pass in parameters when in use. If you want to pass in parameters in the use of the decorator, you can encapsulate another layer of function outside the decorator.

Class Example {@ log (1) instanceMethod () {} @ log (2) static staticMethod () {}} function log (id) {return (target, methodName, descriptor) = > {const oldValue = descriptor.value; descriptor.value = function () {console.log (`Calling ${name} with`, arguments, `this id is ${id} `); return oldValue.apply (this, arguments);}; return descriptor;}}

The decorator implemented in the above code can be used to pass parameters so that the behavior of the decorator can be modified according to different scenarios.

Execution order of class decorator and class method decorator

If the decorator is used to decorate both the class and the class's methods in a class, the order of execution of the decorator is: execute the class method's decorator first, then execute the class decorator.

If the same class or the same class method has more than one decorator, it will enter from the outside to the inside, and then execute from the inside to the outside, just like peeling an onion.

/ / Class decorator function decoratorClass (id) {console.log ('decoratorClass evaluated', id); return (target) = > {/ / constructor of target class console.log (' constructor of class target:', target) console.log ('decoratorClass executed', id);}} / / method decorator function decoratorMethods (id) {console.log (' decoratorMethods evaluated', id) Return (target, property, descriptor) = > {/ / target represents / / process.nextTick (() = > {target.abc = 123 console.log ('method target',target) / /})) console.log (' decoratorMethods executed', id) } @ decoratorClass (1) @ decoratorClass (2) class Example {@ decoratorMethods (1) @ decoratorMethods (2) method () {}} / * * enter the log * * / / decoratorMethods evaluated 1 decoratorMethods evaluated / method target Example {abc: 123} / / decoratorMethods executed 2 hand / method target Example {abc: 123} / / decoratorMethods executed 1 hand / decoratorClass evaluated 1 hand / decoratorClass evaluated 2 hand / target constructor: [Function: Example] / / decoratorClass The constructor of the executed 2ax / target class: [Function: Example] / / decoratorClass executed 1

As in the above code, the class method decorators @ decoratorMethods (1) and @ decoratorMethods (2) are executed first, and then the class decorators @ decoratorClass (1) and @ decoratorClass (2) are executed.

In the class method decorator in the above code, the outer decorator @ decoratorMethods (1) enters first, but the inner decorator @ decoratorMethods (2) executes first. The same goes for class decorators.

Using decorator to realize AOP section programming function log (target, name, descriptor) {var oldValue = descriptor.value; descriptor.value = function () {console.log (`Calling "${name}" with`, arguments); return oldValue.apply (null, arguments);} return descriptor;} / / Log application class Maths {@ log add (a, b) {return a + b;} const math = new Maths () / / passed parameters should get logged nowmath.add (2,4); at this point, the study on "how to implement decorators in es6" is over. I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report