Project address github.com/LuckyChou71…

Configure the decorator environment

{
  "name": "decorator"."version": "1.0.0"."main": "index.js"."license": "MIT"."dependencies": {
    "@babel/cli": "^ 7.13.16"."@babel/core": "^ 7.13.16"."@babel/plugin-proposal-class-properties": "^ 7.13.0"."@babel/plugin-proposal-decorators": "^ 7.13.15"."@babel/preset-env": "^ 7.13.15"
  },
  "scripts": {
    "start": "npx babel src/index.js --out-dir dist && node dist/index.js"}}Copy the code

Create a package.json file to copy the above content and install the dependencies

Then create a file in the root directory. Babelrc configure the following

Because the latest version of the Babel plug-in is pluggable, just installing it won’t work and you need to configure it

{
  "presets": ["@babel/preset-env"]."plugins": [["@babel/plugin-proposal-decorators",
      {
        "legacy": true}], ["@babel/plugin-proposal-class-properties"]]}Copy the code

Finally, create a jsconfig.json file and write down the following configuration to turn on the decorator or the compiler will warn us

{
  "compilerOptions": {
    "target": "es6"."experimentalDecorators": true}}Copy the code

Then create a new SRC directory and create the index.js file in it, and we’ll write our code in that file

decorator

Parameters are classes that are decorated by decorators

Modifying member variables

There are three parameters

  • Target is a constructor for a static member and a prototype object for an instance member

  • Name Specifies the name of the member to be decorated

  • Descriptor Property descriptor of the member to be modified

The specific code is as follows

@log1
class MyClass {
  constructor() {
    this.name = 'chou';
  }
  @log2
  getName() {
    console.log(this.name);
  }
  @log2 name = 'chou';
  @log2 static age = 18;
}

/ * * * *@param {*} Target The class to be decorated with */
function log1(target) {
  target.prototype.logger = () = > console.log(I was `${target.name}Class `);
}

/ * * * *@param {*} Target is a constructor for static members and a prototype object for instance members@param {*} Name Specifies the name of the member to be decorated@param {*} Descriptor is modified properties of the member descriptors enumerable & configurable & writable |, initializer * /
function log2(target, name, descriptor) {
  // target.log = () => console.log('log')
  console.log('target:', target);
  console.log('name:', name);
  console.log('descriptor:', descriptor);
}

const test = new MyClass();
test.logger();
Copy the code

Decorators give us the ability to change methods and variables inside a class