
上QQ阅读APP看书,第一时间看更新
Accessor decorators
Accessor decorators are prefixed before the accessor declaration. These decorators are used to observe, modify, or replace an accessor definition and are applied to the property descriptor. The following code snippet shows a simple class with the applied accessor decorator applied:
class Customer { private _firstname: string; private _lastname: string; constructor(firstname: string, lastname: string) { this._firstname = firstname; this._lastname = lastname; } @logging(false) get firstname() { return this._firstname; } @logging(false) get lastname() { return this._lastname; } }
In this class, we decorate the get accessor of firstname and lastname with @logging and pass boolean to enable or disable logging. The following code snippet shows the function for the @logging decorator:
function logging(value: boolean) { return function (target: any, propertyKey: string, descriptor:
PropertyDescriptor) { descriptor.logging = value; }; }
The logging function sets the Boolean value to the logging property descriptor.