白筱汐

想都是问题,做都是答案

0%

JavaScript设计模式——装饰器模式

介绍

装饰者模式,又称装饰器模式,在不改变原对象的基础上,通过对其添加属性或方法来进行包装拓展,使得原有对象可以动态具有更多功能。

js代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Component {
operation() {
console.log('基础组件操作');
}
}

class Decorator {
constructor(component) {
this.component = component
}

operation() {
this.component.operation()
this.newOperation()
}

newOperation() {
console.log('装饰器额外的操作')
}
}

let component = new Component()
let decorator = new Decorator(component)
decorator.operation()

ts代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// https://wangdoc.com/typescript/decorator
function simpleDecorator(
value:any, // 当前类本身
context:any // conetext.name 为字符串 class
) {
console.log(`hi, this is ${context.kind} ${context.name}`);
return value;
}

@simpleDecorator
class A {
operation() {
console.log('基础组件操作');
}
}

const a = new A()

装饰器的语法有新旧的变化,代码使用较新的装饰器语法,详情请查看 阮一峰的 typescript 教程,装饰器