ES6 decorator

Many object-oriented languages have Decorator functions that modify, or comment on, the behavior of a class. Js is no exception.

What can decorators do

  • The type determination of the passed parameter
  • Sorting and filtering of return values
  • Add throttling, stabilization, or other functional code to the function
  • A variety of repetitive code that has nothing to do with the function logic itself, based on multiple class inheritance
  • Wait…

Decorator basic syntax

@decorator class MyClass {}; // same as class MyClass {}; A = decorator(MyClass ) || MyClass ;Copy the code

As you can see from above, a decorator is a function that handles a class. The first argument to the decorator function is the target class to be modified.

Function decorator(target) {here you can add attributes, methods, and other operations to the class. }Copy the code

Decorator execution order

Multiple decorators in the same place follow the onion model, entering from outside to inside and executing from inside to outside (same as Koa’s onion model)

function dec(id){
    console.log('evaluated', id);
}

class Example {
    @dec(1)
    @dec(2)
    method(){}
}
// evaluated 1
// evaluated 2
Copy the code

Methods that modify classes (implement a readonly decorator for attributes)

Class Person {@readonly name() {return "I am XXX"}} function readonly(target){// target object's original value is as follows: specifiedFunction, // enumerable: false, // configurable: true, // writable: true // }; target.writable = false; }Copy the code

Pay attention to

  • Decorators in JS can only modify classes and attributes, not independent functions, which have variable promotion.
  • Decorators change the behavior of classes at compile time, not at run time.
  • Decorators can run code at compile time.
  • The order of decorators is very important.
  • Reasonable use of decorators can greatly improve the efficiency of development, packaging and refining some non-logical related code can help us quickly complete repetitive work, save time.
  • A large number of decorators can lead to unreadability enhancement. Use with caution.

reference

1, JS Decorator scene in action

Introduction to ECMAScript 6 — Ruan Yifeng