This is the 24th day of my participation in Gwen Challenge

The definition and elementary usage of ornaments

What is a decorator

Defining a decorator is itself a function that decorates a class

Function testUser(cons:any){cons.prototype.getName=(name:string)=>{function testUser(cons:any){ Console. log('name',name)}} function testUser01(cons:any){cons.prototype.getName=(name:string)=>{console.log('name',name)}} function testUser01(cons:any){ console.log('name',name) } } function playUser(){ return (cons:any) =>{ console.log(123); }} // Decorators are only used once when the class is defined and not when the class instance is created. // The order in which decorators are executed is from bottom to top and from right to left. @testUser@testUser01 User{} let user = new User(); (user as any).getName(' luoyang white peony ');Copy the code

A more standardized way of writing decorators

Example:

Function testDecorator<T extends new (... args: any[])=> any >(constructor:T){ return class extends constructor{ getName(){ return this.name; } } } @testDecorator class Play{ constructor(name:string){ } } let paly = new Play('wang') let getname = (paly as any).getName(); Function PlayWrap(){return function xiushiPlayer<T extends new (... args:any[])=> any>(constructor:T){ return class extends constructor{ setName(){ this.name = 'kedaya'; return this.name; }}}} // Let newPlayer = PlayWrap()(class Gamer{constructor(palyer:string){console.log('palyer',palyer)}})  let palys = new newPlayer('wangpeng'); let getName:string = palys.setName();Copy the code

Type of decorator constructor

function newPlay<T extends new((... args:any[])=>any)>(cons)Copy the code

Decorators for methods inside a class

Example:

// Method decorator // The normal method target corresponds to the method's prototype. // The static method target corresponds to the method's constructor, function getNameDecorator(target:any,key:string, Discriptor: PropertyDescriptor) {/ / setting method can rewrite can't rewrite the false discriptor. Writable = false; Discriptor. value; // See what the original trim is. } class Player{ // private name:string = ''; constructor(private name:string){} get getName(){ return this.name; } @getNameDecorator setName(name:string){ this.name = name; } } let player = new Player('zerDa'); player.setName('dijia'); console.log('2131',player)Copy the code