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

  • Expert Angular
  • Mathieu Nayrolles Rajesh Gunasundaram Sridhar Rao
  • 189字
  • 2021-07-15 17:05:34

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.

主站蜘蛛池模板: 阜城县| 白山市| 安阳县| 如皋市| 迁西县| 蓬溪县| 大石桥市| 山阴县| 拜城县| 左权县| 舟曲县| 新绛县| 怀宁县| 泉州市| 云南省| 抚州市| 宁南县| 潼南县| 麻江县| 五原县| 新泰市| 淮阳县| 调兵山市| 桦南县| 尤溪县| 松溪县| 永和县| 南阳市| 桓仁| 项城市| 余江县| 砚山县| 凤城市| 牟定县| 博罗县| 多伦县| 忻州市| 通城县| 株洲县| 故城县| 启东市|