Appearance
装饰器
装饰器和继承的区别
环境配置
- tsc --init
- 开启
和
配置项 - tsc -w
类装饰器
不使用语法糖
ts
const moveDecorator: ClassDecorator = (target: Function) => {
target.prototype.getPosition = (): { x: number; y: number } => {
return { x: 100, y: 230 }
}
}
class Tank {}
const t = new Tank()
moveDecorator(Tank)
console.log(t.getPosition())
语法糖
ts
const moveDecorator: ClassDecorator = (target: Function) => {
target.prototype.getPosition = (): { x: number; y: number } => {
return { x: 100, y: 230 }
}
}
@moveDecorator
class Tank {}
const t = new Tank()
console.log(t.getPosition())
装饰器的叠加
INFO
装饰器是可以叠加的
ts
const MoveDecorator: ClassDecorator = (target: Function) => {
target.prototype.getPosition = (): { x: number; y: number } => {
return { x: 100, y: 230 }
}
}
const MusicDecorator: ClassDecorator = (target: Function) => {
target.prototype.playMusic = (): void => {
console.log('播放音乐')
}
}
@MoveDecorator
@MusicDecorator
class Tank {}
const t = new Tank()
console.log(t.getPosition())
console.log(t.playMusic())
例子:全局统一消息提示
ts
const MessageDecorator: ClassDecorator = (target: Function) => {
target.prototype.message = (content: string) => {
console.log({
code: 200,
success: true,
message: content,
})
}
}
@MessageDecorator
class LoginController {
public login() {
console.log('登录业务处理')
this.message('登录成功消息')
}
}
new LoginController().login()
@MessageDecorator
class ArticleController {
public getList() {
console.log('获取文章列表处理')
this.message('获取文章列表成功')
}
}
new ArticleController().getList()
装饰器工厂
是一个函数,返回值是一个类装饰器const xxDecoratorFactory = ():ClassDecorator => {}
,可以接收多个参数
ts
function MusicDecoratorFactory(type: string): ClassDecorator {
switch (type) {
case 'tank':
return (target: Function) => {
target.prototype.playMusic = (): void => {
console.log('播放坦克音乐')
}
}
case 'player':
return (target: Function) => {
target.prototype.playMusic = (): void => {
console.log('播放玩家音乐')
}
}
default:
return (target: Function) => {
target.prototype.playMusic = (): void => {
console.log('播放默认音乐')
}
}
}
}
@MusicDecoratorFactory('tank')
class Tank {}
const t = new Tank()
console.log(t.playMusic())
@MusicDecoratorFactory('player')
class Player {}
const p = new Player()
console.log(p.playMusic())
方法装饰器
ts
``
### 例子:模拟代码高亮
### 例子:代码延迟执行
### 装饰器工厂:例子-代码延迟执行
### 例子:全局异常管理
### 登录验证的实现
## 属性装饰器和参数装饰器