The target
Implement a decorator
The main points of
- What is a decorator
- How do decorators work
- Implement a simple decorator
A decorator
-
A decorator is a special type of declaration that is essentially a method that can be injected into classes, methods, properties, and parameters to extend their functionality.
-
Common decorators: class decorators, attribute decorators, method decorators, parameter decorators…
-
Decorator can be written as: normal decorator (can not be added), decorator factory (can be added)
-
Decorators are a standard feature of ES7!
How to use
No parameters
function Path(target:any) {
console.log("I am decorator.")}@Path
class RouterService {}
Copy the code
After compiling using TSC, run the node xxx.js command. The following output is displayed:
I am decorator.
Copy the code
A parameter
function Path(p1: string, p2: string) {
return function (target) { // This is the real decorator
// do something }}@Path("/user"."userId")
class RouterService {}
Copy the code
Implement a simple decorator
export function measure(target: any, name: any, descriptor: any) {
const oldValue = descriptor.value;
descriptor.value = async function() {
const start = Date.now();
const ret = await oldValue.apply(this.arguments);
console.log(`${name}Perform time-consumingThe ${Date.now() - start}ms`);
return ret;
};
return descriptor;
}
@measure
// The execution time of the function is recorded 🕓🕝🕤
class RouterService {}
Copy the code