JavaScript: Implementing a lazy man LazyMan

Javascript: Implement LazyMan

demand

LazyMan(“Jane”)输出:
Hi! This is Jane!
    
LazyMan(“Jane”).sleep(20).eat(“dinner”)输出
Hi! This is Jane!
//等待20秒..
Wake up after 20
Eat dinner~
    
LazyMan(“Jane”).eat(“dinner”).eat(“supper”)输出
Hi This is Jane!
Eat dinner~
Eat supper~
    
LazyMan(“Jane”).sleepFirst(5).eat(“supper”)输出
//等待5秒
Wake up after 5
Hi This is Jane!
Eat supper~

Code

function Lazyman(name){
    
    
    return new _lazyman(name);
}

function _lazyman(name){
    
    
	//创建任务队列
    this.task = [];
    //保存指向lazyman的this,以供给闭包使用
    let _this = this;
    //默认问好
    let fn = (function(name){
    
    
        return ()=>{
    
    
            console.log(`Hi! This is${
      
      name}`);
            //完成任务后执行下一个任务
            _this.next();
        }
    })(name);
	//将此任务存入任务队列
    this.task.push(fn);
    //启动第一个任务
    setTimeout(()=>{
    
    
        this.next();
    },0);
}

_lazyman.prototype = {
    
    
	//拿出队列中的第一个任务并执行
    next : function(){
    
    
        let fn = this.task.shift();
        fn && fn();
    },
    eat : function(food){
    
    
        let fn = (food=>{
    
    
            return ()=>{
    
    
                console.log(`Eat ${
      
      food}~`);
                this.next();
            }
        })(food);
        this.task.push(fn);
        return this;
    },
    sleep : function(time){
    
    
        let fn = (time=>{
    
    
            return ()=>{
    
    
                console.log(`Wake up after ${
      
      time}s`)
                //阻塞下一个任务
                setTimeout(()=>{
    
    
                    this.next();
                },time*1000);
                
            }
        })(time);
        this.task.push(fn);
        return this;
    },
    sleepFirst : function(time){
    
    
        let fn = (time=>{
    
    
            return ()=>{
    
    
                console.log(`wake up after ${
      
      time}s`);
                setTimeout(()=>{
    
    
                    this.next();
                },time*1000);  
            }
        })(time);

        this.task.unshift(fn);
        return this;
    }
}

Results of the

Lazyman('yivi').sleepFirst(3).eat('peach').sleep(2).eat('apple')

wake up after 3s
Hi!This is yivi!
Eat peach~
wake up after 2s
Eat apple~

to sum up

This question involves chain calls, event loops, closures, and observer mode. You can look back at this question after learning ES6 related knowledge, and the idea will be much clearer!

Guess you like

Origin blog.csdn.net/yivisir/article/details/107899020