3.方法裝飾器:
它會被應用到方法的屬性描述符上,可以用來監聽,修改或者替換方法定義。
方法裝飾會在運行時傳入下列三個參數:
(1)對於靜態成員來說是類的構造函數,對於實例成員是類的原型對象
(2)成員的名字
(3)成員的屬性描述
function get(params: any) { return function (target: any, methodName: any, desc: any) { console.log(target); console.log(methodName); console.log(desc); // 擴展屬性 target.apiUrl = 'xxx'; // 擴展方法 target.run = function () { console.log('run'); } // 修改裝飾器的方法,把裝飾器方法里面傳入的參數都改為string類型 // (1)保存當前的方法 let oMethod = desc.value; // (2)改寫方法 desc.value = function (...arr: any[]) { arr = arr.map(e => { return String(e); }) // 調用未改寫的方法 oMethod.apply(this, arr); console.log(arr); } } } class HttpClient { public url: any | undefined; constructor() { } @get('http://www.baidu.com') getData(...arr: any[]) { console.log('我是getData里面的方法'); } } let http: any = new HttpClient(); console.log(http.apiUrl); http.getData('張三', 25);
2.方法參數裝飾器
參數裝飾器表達式會在運行時當作函數被調用,可以使用參數裝飾器為類的原型增加一些元素數據,傳入下列三個參數:
- 對於靜態成員來說是類的構造函數,對於實例成員是類的原型對象
- 參數的名字
- 參數在函數參數列表中的索引
function logParams(params: any) { return function (target: any, methodName: any, paramsIndex: any) { console.log(1, params); console.log(2, target); console.log(3, methodName); console.log(4, paramsIndex); // 增加屬性 target.apiUrl = params; } } class HttpClient { public url: any | undefined; constructor() { } getData(@logParams('uuid') uuid: any) { console.log('我是getData里面的方法,uuid=', uuid); } } let http = new HttpClient(); http.getData(123456); console.log(5, http.apiUrl);
待完善
