zoukankan      html  css  js  c++  java
  • TypeScript 装饰器实例

    const userInfo: any = undefined;
    
    class Test{
      getName() {
        return userInfo.name;
      }
      getAge() {
        return userInfo.age;
      }
    }
    
    const test = new Test();
    test.getName();
    这个例子运行的时候会报错,因为 name,age 不存在,userInfo 是 undefined,进行以下方式处理
     
    const userInfo: any = undefined;
    
    class Test{
      getName() {
        try {
          return userInfo.name;
        } catch (e) {
          console.log('userinfo.name 不存在')
        }
      }
      getAge() {
        try {
          return userInfo.info;
        } catch (e) {
          console.log('userinfo.info 不存在')
        }
      }
    }
    
    const test = new Test();
    test.getName();
    假设这里有很多getName,getAge 的方法,很多的 try...catch 代码会变得很长,我们用装饰器解决 try...catch 反复编写的问题
     
    const userInfo: any = undefined;
    
    function catchError(target: any, key: string, descriptor: PropertyDescriptor) {
      const fn = descriptor.value;
      descriptor.value = function () {
        try {
          fn();
        } catch (e) {
          console.log('userinfo 存在问题')
        }
      }
    }
    
    class Test{
      @catchError
      getName() {
       return userInfo.name;
      }
      @catchError
      getAge() {
       return userInfo.info;
      }
    }
    
    const test = new Test();
    test.getAge();
  • 相关阅读:
    HanTTS简单文档
    一张包含所有颜色的图片
    shiro整合SpringMVC基于xml
    设计模式-享元模式
    关于volatile关键字实现的个人理解
    重量级锁
    轻量级锁
    偏向锁
    Seata概念的总结
    苹果手机怎么把资源库的APP放到桌面
  • 原文地址:https://www.cnblogs.com/wzndkj/p/13488668.html
Copyright © 2011-2022 走看看