console
class LazyMan {
// 定义一个消息队列,存放函数
queue = []
constructor(name) {
this.sayName(name)
// 开始调用第一个
setTimeout(() => this.next(), 0)
}
sayName(name) {
this.queue.push(() => {
console.log(`this is ${name}`)
this.next()
})
}
sleep(time) {
this.queue.push(() => {
setTimeout(() => {
console.log(`wake up after ${time}`)
this.next()
}, time * 1000)
})
// 返回自己,可实现链式编程
return this
}
eat(food) {
this.queue.push(() => {
console.log(`eat ${food}`)
this.next()
})
return this
}
sleepFirst(time) {
this.queue.unshift(() => {
setTimeout(() => {
console.log(`wake up after ${time}`)
this.next()
}, time * 1000)
})
return this
}
next() {
// 第一项弹出来执行
const fn = this.queue.shift()
fn && fn()
}
}
console.log(new LazyMan('hank').sleepFirst(2).eat('supper').sleep(2))
1.考察了class的链式用法<br>
2.数组实现消息队列<br>
把要执行的函数放入数组中,但一个执行完,通知另一个弹出