处理类中的get/set函数,使用方式与方法装饰器相同
function getDesc ( target: Function, name: string, descriptor: PropertyDescriptor ) {}
- 参数说明
- target:静态成员:类的构造函数;实例成员:类的原型对象
- name:成员的名称
- descriptor:属性描述符,详情看
Object.defineProperty
- configurable:是否可配置,再次配置描述符
- writeable:值是否可重写,重新复制
- enumerable:是否可枚举,遍历
- value:属性的值,即被装饰的函数,可通过该描述符替换方法的声明
- get/set:存取器,geter/seter
- TS不允许同时装饰一个成员的geter和seter,两者为一整体,只需要在其中一个上声明
- 如果装饰器返回一个值,那么这个值会作为该成员的属性描述符对象(descriptor)
示例
function getDesc ( bool: boolean ) {
return function ( target: Function, name: string, descriptor: PropertyDescriptor ) {
return {
value () {
console.log('can not say')
},
enumerable: bool
}
}
}
class ClassName {
private _name: string = '阿坤'
@getDesc(false)
get name () {
return this._name
}
set name (value: string) {
this._name = value
}
}