class Person {
constructor(name) {
this.name = name
setTimeout(() => {
this.next()
}, 0)
}
tasks = []
sleep(time) {
const fn = () => {
console.log(`${this.name}开始睡觉`)
setTimeout(() => {
console.log(`${this.name}睡醒了`)
this.next();
}, time * 1000)
}
this.tasks.push(fn)
return this
}
run() {
const fn = () => {
console.log(`${this.name}跑了个步`)
this.next();
}
this.tasks.push(fn)
return this;
}
eat(a) {
const fn = () => {
console.log(`${this.name}吃了个${a}`)
this.next();
}
this.tasks.push(fn)
return this;
}
next() {
const fn = this.tasks.shift();
fn && fn()
}
}
new Person('小明').sleep(2).run().eat('午饭')
.sleep(2).eat('晚饭')
JS笔试:JS链式调用
最新推荐文章于 2023-08-29 14:06:16 发布