装饰器

装饰器 装饰模式 ,在执行之前可以进行包装
注意:只能装饰类(或类中的属性、方法),装饰器必须是一个函数

装饰器是对类、函数、属性之类的一种装饰,可以针对其添加一些额外的行为。
通俗的理解可以认为就是在原有代码外层包装了一层处理逻辑。

语法:
@函数名
class Circle {}
  • 装饰类

装饰类,装饰器的参数(Constructor)是类本身

@type1
@type2
class Circle{}
function type1(Constructor){
Constructor.type1 = type1
}
function type2(Constructor){
 Constructor.type2 = type2
}
注意:装饰器后面不能带;(分号),执行顺序是就近原则先执行type1在执行type2
注意:装饰器必须是一个函数所以type1的返回值必须是函数,执行顺序type1(),type2(),type2,type1
@type1('哺乳1')
@type2('哺乳2')
class Circle{
    @readonly PI = 3.14;
}
function type1(type1){
    console.log('t1')
    return function(Constructor){
        console.log('innerT1')
        Constructor.type1 = type1
    }
}
function type2(type2){
    console.log('t2')
    return function(Constructor){
        console.log('innerT2')
        Constructor.type2 = type2
    }
}
  • 装饰属性

装饰属性装饰器的参数分别是 类的原型装饰的keykey对应的属性描述器(里面有一些属性 例:是否可改、是否可枚举…)

class Circle{
    @readonly PI = 3.14;
}
function readonly(CirclePrototype,key,descriptor){
    descriptor.writable = false;
    descriptor.enumerable = false;
}
  • 装饰方法

装饰方法装饰器的参数分别是 类的原型装饰的keykey对应的属性描述器(里面有一些属性 例:是否可改、是否可枚举…)

class Circle{
    @before
    say(){
        console.log('say')
    }
}
function before(CirclePrototype,key,descriptor){
    let oldSay = descriptor.value; // 函数劫持
    descriptor.value = function(){ // 将函数原有的逻辑 进行包装
        console.log('before')
        oldSay()
    }
}
  • 装饰器例子:
// mixin 混合

let obj = {
    name:'zf',
    age:'10',
}
@mixin(obj)
class School{

}
function mixin(obj){
   return function(Constructor){
    Object.assign(Constructor.prototype,obj)
   }
}
let school = new School;
console.log(school.name,school.age); 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值