关于链式调用的实例 JS

最近被问到这样一个问题,如下:
Man('hi').eat('fish').eat('rice').finishSleep(2000)
需求是:

  • 1、若没有调用finishSleep,则顺序打印 hi , fish , rice
  • 2、若调用finishSleep, 则顺序打印 2000, hi , fish , rice
    鄙人粗略实现如下(欢迎更牛逼的写法,请在下方留言讨论):
function Man(str) {
  Man.prototype.fnArr = []
  Man.prototype.fnArr.push(log(str))
  Man.prototype.exec()
  return Man;
}

function log(str) {
  return function () {
    console.log(str)
  }
}

Man.eat = function (str) {
  Man.prototype.fnArr.push(log(str))
  Man.prototype.exec()
  return Man;
}

Man.finishSleep = function(n) {
  Man.prototype.fnArr.unshift(log(n))
  Man.prototype.exec()
  return Man;
}

Man.prototype.exec = function () {
  clearTimeout(Man.prototype.st)
  Man.prototype.st = setTimeout(() => {
    for (const fn of this.fnArr) {
      fn()
    }
  }, 0);
}
Man('hi').eat('fish').eat('rice')
// log: hi , fish , rice
Man('hi').eat('fish').eat('rice').finishSleep(2000)
// log: 2000, hi , fish , rice
展示评论