TypeScript 裝飾器例項
阿新 • • 發佈:2020-08-12
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() {假設這裡有很多getName,getAge 的方法,很多的 try...catch 程式碼會變得很長,我們用裝飾器解決 try...catch 反覆編寫的問題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();
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();