装饰器
什么是装饰器
装饰器的使用场景
class Animal { type: string constructor(type: string) { this.type = type } greet() { console.log(`Hello, I'm a(n) ${this.type}!`) } } const xcat = new Animal('cat') xcat.greet() // Hello, I'm a(n) cat!class Xcat extends Animal { constructor() { super('cat') } greet() { console.log('meow~ meow~') super.greet() } } const xcat = new Xcat() xcat.greet() // meow~ meow~ // Hello, I'm a(n) cat!class Animal { type: string constructor(type: string) { this.type = type } @yelling greet() { console.log(`Hello, I'm a(n) ${this.type}!`) } } const typeToYellingMap = { cat: 'meow~ meow~' } function yelling(originalMethod: any, context: ClassMethodDecoratorContext) { return function(...args: any[]) { console.log(typeToYellingMap[this.type]) originalMethod.call(this, ...args) } } const xcat = new Animal('cat') xcat.greet() // meow~ meow~ // Hello, I'm a(n) cat!@injectable class Dog implements IAnimal { sayHi() { console.log('woof woof woof') } } @injectable class Cat implements IAnimal { sayHi() { console.log('meow meow meow') } } class AnimalService { constructor( @inject dog: Dog @inject cat: Cat ) { this._dog = dog this._cat = cat } sayHiByDog() { this._dog.sayHi() } sayHiByCat() { this._cat.sayHi() } }class MyService { @recordExecution myFn() { // do something... } } function recordExecution(originalMethod: any, context: ClassMethodDecoratorContext) { return function(...args: any[]) { console.time('mark execution') originalMethod.call(this, ...args) console.timeEnd('mark execution') } }
装饰器的类别
context 与 metadata 二三讲
Last updated