装饰器就是相当于给人或事多加一些东西 就是现实中装饰类似的意思 化妆打扮加衣服
装饰器(Decorator)是一种与类(class)相关的语法,用来注释或修改类和类方法与属性。许多面向对象的语言都有这项功能,一般和类class相关 普通函数 不要使用
进入代码就会执行完成
装饰器就是一种函数 ,写成@+函数名,它可以放在类和类方法的定义前面。
装饰类Foo
@frozen
class Foo{
//装饰method方法
@configurable(false)
method(){
//装饰yy方法
@throttle(500)
yy(){}
}
}
1:修饰类 基本形式
//装饰器是一个函数 他可以给类或者属性方法加上一些其他东西
//实现一些代码的复用 大家写习惯之后 代码会简洁
function testable(target){
target.isTestable = true;//相当于给 MyTestableClass.isTestable =true
console.log('我是testable函数')
}
//class类
//在类或者类属性方法前面写上 @函数名,就相当于调用这个函数
@testable
class MyTestableClass{
//...
}
//类似 testable( MyTestableClass)
function testable(isTestable){
return function(target,...rest){
console.log('参数',rest)
target.isTestable = isTestable
}
}
@testable(true) //相当于先testable(true) 返回函数 再@函数
class MyTestableClass{}
console.log('add-MyTestableClass',MyTestableClass.isTestable) //true
// 类 方法 属性 有三个参数
function readonly(target,name,descriptor){
console.log('target',target) //当前的person
console.log('name',name) //你装饰的那个属性或者方法名
console.log('descriptor',descriptor)
//descriptor对象原来的值如下
{
configurable:false,//能否使用delete 能否需改属性特性、或能否修改访问器属性、false为不可重新定义,默认值为true
enumerable: false,//对象属性是否可通过for-in循环,flase为不可循环,默认值为true
writable:false,//对象属性是否可修改,flase为不可修改,默认值为true
value:'xiaoming' //对象属性的默认值
};
descriptor.writable = false;
return descriptor
}
class Person {
//可以在类之前用@函数名 装饰器,也可以在类的属性和方法之前
@readonly
abc(){
console.log('我是person的abc函数')
}
//我给xx属性 先用readonly这个装饰器 函数执行一下
//装饰器函数 就是执行函数 帮助下面的属性或者方法 加一些控制条件
//装饰器函数 实现了代码的复用
@readonly
xx=123
}