js链式调用实现
- 队列方式
function People(name) {
if (!(this instanceof People)) {
return new People(name);
}
this.arr = [];
this.arr.push(() => {
console.log(`Hi This is ${name}!`);
this.next();
});
setTimeout(() => {
this.next();
}, 0);
}
People.prototype.next = function () {
if (this.arr.length > 0) {
this.arr.shift()();
}
};
People.prototype.sleepFirst = function (sleepFirstTime) {
this.arr.unshift(() => {
console.log(`等待${sleepFirstTime}秒`);
setTimeout(() => {
console.log(`Weak up after ${sleepFirstTime}`);
this.next();
}, sleepFirstTime * 1000);
});
return this;
};
People.prototype.sleep = function (sleepTime) {
this.arr.push(() => {
console.log(`等待${sleepTime}秒..`);
setTimeout(() => {
console.log(`Weak up after ${sleepTime}`);
this.next();
}, sleepTime * 1000);
});
return this;
};
People.prototype.eat = function (eatContent) {
this.arr.push(() => {
console.log(`Eat ${eatContent}`);
this.next();
});
return this;
};
链式调用
// People("“Jack”").sleep(4).eat("“dinner”");
// People('“Rose”').eat('“dinner”').eat('“supper”')
// People("“John”").sleepFirst(5).eat("“supper”");