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

Property decorators

Property decorators are prefixed to property declarations. They actually redefine the property decorated by adding extra behavior. The signature of PropertyDecorator in the TypeScript source code is as follows:

declare type PropertyDecorator = (target: Object, propertyKey: string | 
symbol) => void;

The following is a code snippet of a class with a property decorator applied to a property:

class Customer { 
  @hashify 
  public firstname: string; 
  public lastname: string; 
  
  constructor(firstname : string, lastname : string) { 
    this.firstname = firstname; 
    this.lastname = lastname; 
  } 
} 

In this code, the firstname property is decorated with the @hashify property decorator. Now, we will see the code snippet of the @hashify property decorator function:

function hashify(target: any, key: string) { 
  var _value = this[key]; 
  
  var getter = function () { 
        return '#' + _value; 
  }; 
  
  var setter = function (newValue) { 
    _value = newValue; 
  }; 
  
  if (delete this[key]) { 
    Object.defineProperty(target, key, { 
      get: getter, 
      set: setter, 
      enumerable: true, 
      configurable: true 
    }); 
  } 
} 

The _value holds the value of the property that is being decorated. Both getter and setter functions will have access to the variable _value and here we can manipulate the _value by adding extra behaviors. I have concatenated # in the getter to return a hash-tagged firstname. Then we delete the original property from the class prototype using the delete operator. A new property will be created with the original property name with the extra behavior.

主站蜘蛛池模板: 旬阳县| 洪雅县| 青阳县| 阿尔山市| 武山县| 宁德市| 南华县| 中西区| 鄯善县| 房产| 鸡东县| 柳江县| 德钦县| 玉屏| 忻城县| 西和县| 大同市| 开江县| 广宁县| 临朐县| 株洲市| 平乡县| 若尔盖县| 郓城县| 扎鲁特旗| 泾源县| 镇平县| 桦川县| 五家渠市| 金秀| 万年县| 巫溪县| 石首市| 金平| 土默特右旗| 拜泉县| 湟中县| 闻喜县| 陵川县| 闽清县| 五华县|