TS之成员装饰器

成员装饰器

属性装饰器

属性装饰器也是一个函数,该函数有两个参数
第一个参数:如果是静态属性,则是类本身(构造函数);如果是实例属性,则是类的原型;
第二个参数:为属性名,固定一个字符串

function t(target:any,str:string){
    console.log(target,target === Test.prototype,str);
}

class Test{
    //实例属性
    @t
    props1:string
    // 静态属性
    @t
   static props2:string
}
/*
Test {} true props1
[Function: Test] false props2
*/
function t(target:any,str:string){
    console.log(target,target === Test.prototype,str);
}
class Test{
    @t
    props1:string
    @t
    props2:string
}
/*
Test {} true props1
Test {} true props2
*/
function t(target:any,str:string){
    console.log(target,target === Test.prototype,str);
    if(!target.__props){
        target.__props = [];
    }
    target.__props.push(str);
}


class Test{
    @t
    props1:string
    @t
    props2:string
}
console.log((Test.prototype as any).__props);
const a = new Test();
console.log((a as any).__proto__)
/*
Test {} true props1
Test { __props: [ 'props1' ] } true props2
[ 'props1', 'props2' ]
Test { __props: [ 'props1', 'props2' ] }
*/

方法装饰器

属性描述符:

const a = new A();
Object.defineProperty(a,'method',{
    writable:false,
    // 遍历
    enumerable:false,
})

方法装饰器也是一个函数,该函数有三个参数
第一个参数:如果是静态方法,则是类本身(构造函数);如果是实例方法,则是类的原型;
第二个参数:为属性名,固定一个字符串
第三个参数:是属性描述符对象

//写成一个函数的形式,美誉为装饰器工厂
function d() {
    return function (target: any, str: string, descriptor: PropertyDescriptor) {
        console.log(target, str, descriptor);
    }
}

class A {
    @d()
    method1() {

    }
}
/**
  A {} 
  
  method1 
  
  {
  value: [Function: method1],
  writable: true,
  enumerable: false,
  configurable: true
  }
 */

方法装饰器的用处

可以对类中的方法进行通用描述,比如方法是否可以遍历,是否过期

function enumerable(target: any, str: string, descriptor: PropertyDescriptor) {
    descriptor.enumerable = true;
}
// 提示方法过期
function useless(target: any, str: string, descriptor: PropertyDescriptor) {
    descriptor.value = function(){
        console.warn('该方法已过期');
    }
}

class A {
    @enumerable
    method1() {
        console.log('方法1')
    }
    @enumerable
    @useless
    method2() {

    }
}
const a = new A();
for (const key in a) {
   console.log(key);
}
a.method1();
a.method2();
/**
   method1
   method2
   方法1
   该方法已过期
 */

方法也可以有多个装饰器,运行顺序还是从下往上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值