1. class Subject { // 被观察者
    2. constructor() {
    3. this.observerList = [] // 搜集观察者
    4. }
    5. add (observer) {
    6. this.observerList.push(observer)
    7. }
    8. remove (observerId) {
    9. for (let i = 0; i < this.observerList.length; i++) {
    10. if (this.observerList[i].id === observerId) {
    11. this.observerList.splice(i, 1)
    12. break
    13. }
    14. }
    15. }
    16. notice () {
    17. for (const observer of this.observerList) {
    18. observer.response()
    19. }
    20. }
    21. }
    22. class Observer { // 观察者
    23. constructor (id) {
    24. // this.id = uuid() // 假设有uuid的方法
    25. this.id = id
    26. }
    27. response () { // 对通知做出反应
    28. console.log(`我是id-${this.id}, 做出反应`)
    29. }
    30. }
    31. const subject1 = new Subject()
    32. const observer1 = new Observer(1)
    33. const observer2 = new Observer(2)
    34. subject1.add(observer1)
    35. subject1.add(observer2)
    36. subject1.notice()
    37. subject1.remove(1)
    38. subject1.notice()