实现一个LazyMan可以调用如下:LazyMan("Hank")输出:嗨!这是汉克!LazyMan("Hank").sleep(10).eat("dinner")输出嗨!这是汉克!//等待10秒..10点后醒来Eatdinner~LazyMan("Hank").eat("dinner").eat("supper")输出HiThisisHank!Eatdinner~Eatsupper~LazyMan("Hank").sleepFirst(5).eat("supper")output//等待5秒5秒后醒来HiThisisHank!吃夜宵等等。这是一个典型的JavaScript流程控制,问题的关键是如何实现任务的顺序执行。Express中有一个类似的东西叫中间件。这个中间件和我们这里的吃饭、睡觉等任务非常相似。每个中间件执行完后,都会调用next()函数。该函数用于调用下一个中间件。对于这个问题,我们也可以用类似的思路来解决。首先创建任务队列,然后使用next()函数控制任务的顺序执行:function_LazyMan(name){this.tasks=[];变种自我=这个;varfn=(function(n){v??arname=n;returnfunction(){console.log("嗨!这是"+name+"!");self.next();}})(name);这个.tasks.push(fn);setTimeout(function(){self.next();},0);//在下一个事件循环中启动任务}/*事件调度函数*/_LazyMan.prototype.next=function(){varfn=this.tasks.shift();fn&&fn();}_LazyMan.prototype.eat=function(name){varself=this;varfn=(function(name){returnfunction(){console.log("Eat"+name+"~");self.next()}})(name);这个.tasks.push(fn);归还这个;//实现链式调用}_LazyMan.prototype.sleep=function(time){varself=this;varfn=(function(time){returnfunction(){setTimeout(function(){console.log("醒来后"+time+"s!");self.next();},时间*1000);}})(时间);这个.tasks.push(fn);返回这个;}_LazyMan.prototype.sleepFirst=function(time){varself=this;varfn=(function(time){returnfunction(){setTimeout(function(){console.log("醒来后"+time+"s!");self.next();},time*1000);}})(时间);this.tasks.unshift(fn);returnthis;}/*封装*/functionLazyMan(name){returnnew_LazyMan(name);}
