实现lazyMan

class LazyMan {
    constructor(name){
         this.nama = name;
        this.queue = [];
        this.queue.push(() => {
            console.log("Hi! This is " + name + "!");
            this.next();
        })
        setTimeout(()=>{
            this.next()
        },0)
    }

    eat(name){
        this.queue.push(() =>{
            console.log("Eat " + name + "~");
            this.next()
        })
        return this;
      }
      
      next(){
        var fn = this.queue.shift();
        fn && fn();
      }

      sleep(time){
        this.queue.push(() =>{
            setTimeout(() => {
                console.log("Wake up after " + time + "s!");
                this.next()
            },time * 1000)
        })
        return this;
    }

    sleepFirst(time){
        this.queue.unshift(() =>{
            setTimeout(() => {
                console.log("Wake up after " + time + "s!");
                this.next()
            },time * 1000)
        })
        return this;
    }

}

function creatLazyMan(name){
    return new LazyMan(name)
}
creatLazyMan("Hank").sleep(10).eat("dinner")
// Hi! This is Hank!
// Wake up after 10s!
// Eat dinner~
原文地址:https://www.cnblogs.com/AwenJS/p/12713115.html