js链式调用
Opened this issue · 0 comments
chunhuigao commented
问题
const boy = new PlayBoy('Tom')
boy.sayHi().sleep(1000).play('王者').sleep(2000).play('跳一跳')
// 输出
// Tom
// 1s 之后
// 王者
// 2s 之后
// 跳一跳
代码
function PlayBoy(name) {
this.val = [];
this.idx = 0;
this.sayHi = () => {
console.log(`大家好,我是${name}`);
return this;
};
this.sleep = (time) => {
setTimeout(() => {
console.log(this.val[this.idx++]);
}, time);
return this;
};
this.play = (val) => {
this.val.push(val);
return this;
};
return this;
}
const boy = new PlayBoy('Tom');
boy.sayHi().sleep(1000).play('王者').sleep(2000).play('跳一跳');