- Expert Angular
- Mathieu Nayrolles Rajesh Gunasundaram Sridhar Rao
- 236字
- 2021-07-15 17:05:35
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.
- C語(yǔ)言程序設(shè)計(jì)教程
- Mastering Adobe Captivate 2017(Fourth Edition)
- 新一代通用視頻編碼H.266/VVC:原理、標(biāo)準(zhǔn)與實(shí)現(xiàn)
- Network Automation Cookbook
- Hands-On Automation Testing with Java for Beginners
- Learning Concurrent Programming in Scala
- HTML 5與CSS 3權(quán)威指南(第3版·上冊(cè))
- Unity 2017 Mobile Game Development
- Mastering Unity 2D Game Development(Second Edition)
- NoSQL數(shù)據(jù)庫(kù)原理
- CoffeeScript Application Development Cookbook
- Spring+Spring MVC+MyBatis從零開(kāi)始學(xué)
- Visual Basic程序設(shè)計(jì)(第三版)
- C++程序設(shè)計(jì)教程(第2版)
- HTML5移動(dòng)前端開(kāi)發(fā)基礎(chǔ)與實(shí)戰(zhàn)(微課版)