- 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() // 不矛盾,可以这样...
}
}