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

The role of the Decorator modifier

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly explains "the function of Decorator modifier". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn the function of Decorator modifier.

Decorator is a proposal of ES7. Readers familiar with the javascript design pattern must know how troublesome it is to implement the modifier pattern with es5 syntax, while using ES7's modifier itself to implement the modifier pattern, the modifier has two main functions:

Sharing method between different classes

Change the behavior of classes and methods at compile time

First, let's take a look at the syntax of decorator:

Decorator is a function, this function can not only modify the class, but also modify the properties and methods of the class, decorator can only pass one parameter when decorating the class, this parameter refers to the modified class, decorator can pass three parameters when modifying the attributes in the class, target refers to the class itself, key is modified attribute, descriptor attribute descriptor.

The following is a demonstration of how to use deractor. The first is to decorate the class with deractor. The code is as follows:

@ setProp

Class User {}

Function setProp (target) {

Console.log (target)

Target.age = 30

}

Console.log (User.age)

The printed result is as shown in the figure:

We use modifiers to add an attribute to the class User, and we can see that target is the class itself.

In the above case, the age property set for the User class is written to death. Can you set a different age by passing parameters when you call the decorator class? Look at the following code:

@ setProp (20)

Class User {}

Function setProp (value) {

Return function (target) {

Target.age = value

}

}

Console.log (User.age)

If we look closely at the code, we find that the modifier is a function, we wrap the modifier in another function, extract the variable as a parameter, call the function where it is used, pass in the parameter, and return the modifier inside the function. this is also the way modifiers are often used in development.

When deractor modifies a class, in addition to directly adding attributes to the class, you can also modify the prototype of the class, as shown in the following code:

We set properties for the prototype of the class through deractor.

After talking about the deractor decorating class, let's count the following: the property and method code of the deractor decorating class is as follows:

Class User {

@ readonly

GetName () {

Return 'Hello World'

}

}

/ / readonly modifies the function to perform read-only operations on the method

Function readonly (target, name, descriptor) {

Console.log (target, name, descriptor)

Descriptor.writable = false

Return descriptor

}

Let u = new User ()

/ / try to modify the function, but an error will be reported in the console

U.getName = () = > {

Return'I will override'

}

Looking at the above code, we first define a class. There is a getName method on the prototype of this class. This method returns hello world, and then defines a deractor. The modifier passes three parameters and prints them. The printed result is as follows:

As you can see, it corresponds to the class itself, the attribute key value, and the attribute descriptor. In the modifier function, we changed the writable of the property descriptor to false, which is read-only and cannot be modified. In the last two lines of code, we define an instance, then modify the getName method of the instance, and the program will report an error.

What are the scenarios in which this modifier is used in practical applications?

Practical application 1: log management in webpack packaging, we often need many steps, such as the first step to read the package.json file, the second step to deal with the file, the third step to load the webpack.base.js file, the fourth step to package. In order to be intuitive, we often print some log files at each step, such as what has been done in this step. It is obvious that the operation of printing the log has nothing to do with the business code at all. We should not mix the log with the business. In this way, the modifier is used to avoid this problem. Here is the code:

Practical application 2: check login this example is commonly used in actual development, before we do some operations, we have to judge whether the user is logged in, compare like, settlement, send on-screen comment. According to the previous way of writing, we have to judge the login status of the user in each method, and then carry on the business operation. Obviously, the precondition and the business are mixed together again. With the modifier, we can solve this problem perfectly. The code is as follows:

Class User {

/ / get the user information of the logged-in user

@ checkLogin

GetUserInfo () {

/ * *

* before, we would have written:

* if (checkLogin ()) {

* / / Business Code

*}

* this code will be executed in every method that requires login

* still the above problem, the premise of execution is mixed with the business again.

, /

Console.log ('get user information for logged-in users')

}

/ / send a message

@ checkLogin

SendMsg () {

Console.log ('send message')

}

}

/ / check whether the user is logged in, and if not, jump to the login page

Function checkLogin (target, name, descriptor) {

Let method = descriptor.value

/ / simulated judgment conditions

Let isLogin = true

Descriptor.value = function (. Args) {

If (isLogin) {

Method.apply (this, args)

} else {

Console.log ('not logged in, about to jump to login page')

}

}

}

Let u = new User ()

U.getUserInfo ()

U.sendMsg ()

Practical application 3: the front end is buried, and sometimes we need to bury it in the work, so as to count the interactive data. The code is as follows:

In the above function, we define a class, which contains some methods that need to be monitored by the buried point, and then we extract the buried point function into the decorator and set parameters for it. Different user actions, pass different parameters, and then, when defining the class, modify the specific methods, so that the code is easy to maintain and the logical expression is clearer.

At this point, I believe you have a deeper understanding of "the role of the Decorator modifier". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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: 295

*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

Internet Technology

Wechat

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

12
Report