es6 decorator

decorator修改类 的行为 (扩展类的功能) 的函数

1.修饰类

@testable
class MyClass{}

function testable(target){
    target.isTestable=true
}

console.log(MyClass.isTestable) // true

也可以在prototype上修改属性,也可以为修饰器添加多个参数。

@testable(false)
class MyAnotherClass{
    
}
function testable(status){
    return target=>{target.prototype.isTestable=status}
}
console.log('MyClass.isTestable',MyAnotherClass.prototype.isTestable) // false

2.修饰方法

//
function readonly(target,key,descriptor){
    descriptor.writable=false
    return descriptor
}

class MyClass{
    @readonly
    print(){return '2021'}
}
let test=new MyClass();
console.log(test.print());

 

posted @ 2021-02-07 21:25  sunmarvell  阅读(49)  评论(0编辑  收藏  举报