TS装饰器
Decorator
1.类装饰器classDecorator
const watcher: ClassDecorator = (target) => {
target.prototype.fn = () => {
console.log('构造函数')
}
}
@watcher
class A {
constructor() {
}
}
let a = new A()
a.fn()
2.装饰器工厂
其实也就是一个高阶函数 外层的函数接受值 里层的函数最终接受类的构造函数
const watcher = (name: string): ClassDecorator => {
return (target: Function) => {
target.prototype.getParams = <T>(params: T): T => {
return params;
}
target.prototype.fn = () => {
console.log(name)
}
}
}
@watcher('xiao123')
class A {
constructor() {
}
}
let a = new A()
a.getParams()
3.可以组合多个装饰器
const watcher = (name: string): ClassDecorator => {
return (target: Function) => {
target.prototype.getParams = <T>(params: T): T => {
return params;
}
target.prototype.fn = () => {
console.log(name)
}
}
}
const watcher1 = (name: string): ClassDecorator => {
return (target) => {
target.prototype.getName = () => {
console.log('name', name)
}
}
}
@watcher('watch')
@watcher1('watcher1')
class A {
constructor() {
}
}
let a = new A()
a.fn()
a.getName()
4.方法装饰器
const watcher: MethodDecorator = (...args) => {
console.log(args)
}
class A {
constructor() {
}
@watcher
run() {
console.log('run')
}
}
const a = new A()
a.run()
5.属性选择器
const watcher: PropertyDecorator = (...args) => {
console.log(args)
}
class A {
@watcher
name: string
constructor() {
}
run() {
console.log('run')
}
}
const a = new A()
6.参数装饰器
//参数装饰器
const met: ParameterDecorator = (...arg) => {
console.log(arg)
}
class Test {
constructor() {
}
setParams(a, @met name: string = '123') {
}
}
const test = new Test()