实现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~

 

posted @ 2020-04-16 15:19  想学JS的前端  阅读(227)  评论(0编辑  收藏  举报