下面是一个小例子,用装饰器来延迟消息发送:

    1. // 利用装饰器来实现消息的延迟
    2. const ResponseMessageDecoratorFactory = (times: number): MethodDecorator => {
    3. return (...args: any[]) => {
    4. const [,, descriptor] = args;
    5. const method = descriptor.value;
    6. descriptor.value = ()=> {
    7. setTimeout(()=> {
    8. method();
    9. }, times);
    10. }
    11. }
    12. }
    13. class Player {
    14. @ResponseMessageDecoratorFactory(2000)
    15. public run() {
    16. console.log('hello,ts!');
    17. }
    18. }
    19. new Player().run()