ts-装饰器(decorator)

  1. tsc --init
// tsconfig.json
{
    "compilerOptions": {
        "experimentalDecorators": true
    }
}
const d: ClassDecorator = function (t) {
  t.prototype.getPosition = function (m) {
        console.log(m)
    }
}
@e
@d // 它先执行
class Person {
login() {
        this.getPosition('登录成功')
    }
}
// 语法糖相当于执行了 d(Person)

let p = new Person()
p.getPosition()

装饰器(Decorator)是一种与类(class)相关的语法,用来注释或修改类和类方法

装饰类
function decorator(target) {
	target.info = 'info' // 静态属性?
}
@decorator
class A {}

// 等同于
class A {}
A = decorator(A) || A;
function dec(obj, fnName) {

    let res = obj[fnName]()
    obj[fnName] = () => {
        return `<h1 style="color: red;">${res}</h1>`
    }
}
class Person {
    @dec
    public cc() {
        return 'hello decorator'
    }
}

document.body.insertAdjacentHTML('beforeend', new Person().cc())

装饰静态方法/普通方法

class Person {
	public static show() {} // protected static 不矛盾吗? 静态方法只能通过类, protected必须类里
}

class Person {
    protected static show() {
        console.log('show');

    }
    cc() {
        Person.show() // 不矛盾,可以这样...
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值