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

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.

主站蜘蛛池模板: 通榆县| 鹤岗市| 莫力| 资溪县| 阳西县| 海门市| 馆陶县| 中方县| 东明县| 新乡县| 敦化市| 恭城| 临高县| 塔河县| 咸阳市| 克山县| 日土县| 平和县| 堆龙德庆县| 综艺| 库尔勒市| 临泉县| 南华县| 扎兰屯市| 筠连县| 城市| 黑龙江省| 肥西县| 濮阳市| 临颍县| 固始县| 新野县| 阳东县| 内黄县| 淄博市| 门头沟区| 遵化市| 革吉县| 石棉县| 定陶县| 诏安县|