<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
class Observer {
constructor () {
this.message = {}
}
on(type,fn) {
if(!this.message[type]){
this.message[type] = [];
}
this.message[type].push(fn);
}
off(type,fn) {
if(!fn) {
delete this.message[type];
return;
}
if(!this.message[type]) return;
this.message[type] = this.message[type].filter(item => item !== fn);
}
trigger(type) {
if(!this.message[type]) return;
this.message[type].forEach(item => {
item();
})
}
}
const person1 = new Observer();
person1.on("情人节",A);
person1.on("情人节",B);
person1.on("端午节",C);
person1.on("端午节",D);
function A() {console.log("买玫瑰花");}
function B() {console.log("买口红");}
function C() {console.log("吃粽子");}
function D() {console.log("赛龙舟");}
</script>
</body>
</html>
console.log(person1);
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210605185326591.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1dpbmRfQU4=,size_16,color_FFFFFF,t_70)
person1.trigger("情人节");
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210605185408372.png)
person1.trigger("端午节");
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210605185436337.png)