senfish / blog

个人技术博客
4 stars 0 forks source link

10. 实现一个GreetRobot,使之具有以下能力 #10

Open senfish opened 3 years ago

senfish commented 3 years ago
// 实现一个GreetRobot,使之具有以下能力
// 1. 执行GreetRobot('bb8')
//    输出: Hi this is bb8!

// 2. 执行GreetRobot('bb8').greet('Bob')
//    输出: Hi this is bb8! 
//         Nice to meet you Bob.

// 3. 执行GreetRobot('bb8').greet('Bob').greet('Jerry')
//    输出: Hi this is bb8! 
//         Nice to meet you Bob.
//         Nice to meet you Jerry.

// 4. 执行GreetRobot('bb8').greet('Bob').greetVip('Mike')
//    输出: Glad to see you Mike~
//         Hi this is bb8!  
//         Nice to meet you Bob.

// 5. 执行GreetRobot('bb8').greetVip('Marry').greetVip('Mike')
//    输出: Glad to see you Mike~
//         Glad to see you Marry~
//         Hi this is bb8!
senfish commented 3 years ago

维护一个数组函数的队列,每个函数负责打印内容; 当所有的函数触发之后,再去执行数组函数

GreetRobot.prototype.greet = function (name) { this.listeners.push(() => console.log(Nice to meet you ${name})); return this; }

GreetRobot.prototype.greetVip = function (name) { this.listeners.unshift(() => console.log(Glad to see you ${name}~)); return this; }

- es6利用类
```js
function GreetRobot(name) {
  return new class {
    constructor() {
      this.listeners = [() => console.log(`Hi this is ${name}!`)];
      this.run();
    }
    run() {
      setTimeout(() => {
        this.listeners.forEach(l => l());
      }, 200)
    }
    greet(name) {
      this.listeners.push(() => console.log(`Nice to meet you ${name}`))
      return this;
    }
    greetVip(name) {
      this.listeners.unshift(() => console.log(`Glad to see you ${name}~`))
      return this;
    }
  }
}