function Man(name) {
this.name = name
this.task = []
let fn = ()=>{
console.log(name)
this.next()
}
this.task.push(fn)
setTimeout(()=>{
this.next()
},0)
return this
}
Man.prototype.eat = function(f){
let fn = ()=>{
console.log('eat', f)
this.next()
}
this.task.push(fn)
return this
}
Man.prototype.sleep = function(time){
let fn = ()=>{
setTimeout(()=>{
console.log('sleep', time)
this.next()
}, time*1000)
}
this.task.push(fn)
return this
}
Man.prototype.sleepFirst = function(time){
let fn = ()=>{
setTimeout(()=>{
console.log('sleepFirst', time)
this.next()
}, time*1000)
}
this.task.unshift(fn)
return this
}
Man.prototype.next = function(){
let fn = this.task.shift()
fn && fn()
}
console.log(new Man('kk').eat('apple').sleep(2).eat('banana').sleepFirst(1))
输出:
sleepFirst 5
kk
sleep 1
eat eeee
eat ddd