实现LazyManInit('Tony').eat('rice').sleep(1000).sleepFirst(2000)

代码是参考别人的,我就加点我写的时候不理解的地方吧。

function LazyMan(name) {
  this.taskList = [];
  console.log(`I am ${name}`);
   setTimeout(() => {
    this.next();
  }, 0)  //setTimeout是异步任务,js会先执行同步任务,这里的同步任务就是把要执行的所有任务推入一个数组。
}


LazyMan.prototype.next = function () {
  if (this.taskList.length > 0) {
    this.taskList.shift()(); //从数组的第一个任务开始执行。
  }
}

LazyMan.prototype.eat = function (food) {
  this.taskList.push(() => {
    console.log(`I am eating ${food}`);
    this.next();  //每个任务执行完弹出下一个任务,这样当前的js执行栈只有这一个任务,就不会出现任务执行顺序错乱。
  })
  return this;
}

LazyMan.prototype.sleep = function (time) {
  this.taskList.push(() => {
    setTimeout(() => {
      console.log(`等待 ${time / 1000} 秒`)
      this.next();
    }, time);
  })
  return this;
}

LazyMan.prototype.sleepFirst = function (time) {
  this.taskList.unshift(() => {
    setTimeout(() => {
      console.log(`先等待 ${time / 1000} 秒`)
      this.next();
    }, time)
  }) //将sleepFirst推入第一个任务,让它不管在什么位置都第二个执行
  return this;
}

function LazyManInit(name) {
  return new LazyMan(name)
}

LazyManInit('Tony').eat('rice').sleep(1000).sleepFirst(2000);

 

posted @ 2020-12-17 10:57  Angular踩坑者  阅读(193)  评论(0编辑  收藏  举报