问题描述
实现一个LazyMan,可以按照以下方式调用:
LazyMan(“Hank”)输出:
Hi! This is Hank!
LazyMan(“Hank”).sleep(10).eat(“dinner”)输出
Hi! This is Hank!
//等待10秒..
Wake up after 10
Eat dinner~
LazyMan(“Hank”).eat(“dinner”).eat(“supper”)输出
Hi This is Hank!
Eat dinner~
Eat supper~
LazyMan(“Hank”).sleepFirst(5).eat(“supper”)输出
//等待5秒
Wake up after 5
Hi This is Hank!
Eat supper
function _LazyMan(name) { this.task = [] this.greet = function (name) { this.task.push(() => { console.log(`Hi This is ${name}!`) this.next() }) } this.greet(name) setTimeout(() => { this.next() }, 0); this.sleep = function (time) { this.task.push(() => { setTimeout(() => { console.log(`Wake up after ${time}`) this.next() }, time) }) return this } this.eat = function (food) { this.task.push(() => { console.log(`Eat ${food}`) this.next() }) return this } this.sleepFirst = function (time) { this.task.unshift(() => { setTimeout(() => { console.log(`Wake up after ${time}`) this.next() }, time); }) return this } this.next = function () { if (this.task[0]) { let fn = this.task.shift() fn() } } } function LazyMan(name) { return new _LazyMan(name) } LazyMan('Hank').sleep(10).eat('dinner').sleepFirst(100)