官术网_书友最值得收藏!

Method decorators

Method decorators are declared before the method declaration. This decorator is used to modify, observe, or replace a method definition and is applied to the property descriptor for the method. The following code snippet shows a simple class with an applied method decorator:

class Hello { 
    @logging 
    increment(n: number) { 
        return n++; 
   } 
} 
 

The Hello class has the increment method that increments a number supplied to its parameter. Note that the increment method is decorated with the @logging decorator to log input and output of the increment method. The following is the code snippet of the logging function:

function logging(target: Object, key: string, value: any) { 
    
        value.value = function (...args: any[]) { 
            var result = value.apply(this, args); 
            console.log(JSON.stringify(args)); 
            return result; 
        } 
    }; 
} 

The method decorator function takes three arguments: target, key, and value. target holds the method that is being decorated; key holds the name of the method being decorated; and value is the property descriptor of the specified property if it exists on the object.

The logging method gets invoked when the increment method is called and it logs the value to the console.

主站蜘蛛池模板: 乐清市| 宜丰县| 武夷山市| 宁晋县| 同仁县| 绥阳县| 云浮市| 青田县| 达尔| 济宁市| 闸北区| 天峻县| 夹江县| 平阴县| 镇原县| 安泽县| 永顺县| 五台县| 铜梁县| 甘孜县| 延津县| 托里县| 沁源县| 固阳县| 农安县| 肃宁县| 林西县| 沙湾县| 武宣县| 商丘市| 兴和县| 西和县| 安阳市| 大丰市| 灵山县| 林周县| 海伦市| 波密县| 吐鲁番市| 红安县| 阳泉市|