SOURCE

class People {
  constructor(name) {
    this.name = name
    this.events = {}
  }

  on (action, event) {
      if (!this.events[event]) this.events[event] = []
      this.events[event].push(event)
  }

  off (action, event) {
      if (this.events[event]) {
          let idx = this.events[event].indexOf(event)
          if (idx >= 0) this.events[event].splice(idx, 1)
      }
  }

  emit (event, word) {
      if (this.events[event]) {
        this.events[event].forEach(item => {
            return item(word)
        })
    }
  }

  sayHi() {
    console.log(`Hi, I am ${this.name}`)
  }
}


/* 以下为测试代码 */
const say1 = (greeting) => {
  console.log(`${greeting}, nice meeting you.`)
}

const say2 = (greeting) => {
  console.log(`${greeting}, nice meeting you, too.`)
}

const jerry = new People('Jerry')
jerry.sayHi()
// => 输出:'Hi, I am Jerry'

jerry.on('greeting', say1)
jerry.on('greeting', say2)

jerry.emit('greeting', 'Hi')
// => 输出:'Hi, nice meeting you.' 和 'Hi, nice meeting you, too'

jerry.off('greeting', say1)
jerry.emit('greeting', 'Hi')
// => 只输出:'Hi, nice meeting you, too'
console 命令行工具 X clear

                    
>
console