快捷导航

想要实现一个class Lazing 函数,输出如下该怎么写?

Lazing('Garry')// 输出 'hello Garray'Lazing('Garry').sleep(10).eat('rice')// 输出 'hello Garray'// 等待10秒...// 输出 'eating rice'Lazing('Garry').eat('rice').eat('bread')// 输出 'eating rice'// 输出 'eating bread'Lazing('Garry').sleepFirst(5).eat('rice')// 等待5秒...// 输出 'hello Garray'// 输出 'eating rice'难点是定时器该怎么处理?如果sleepFirst定时器是后置的怎么来实现?Lazing('Garry').eat('rice').sleepFirst(5)// 等待5秒...// 输出 'hello Garray'// 输出 'eating rice'

免责声明:本内容仅代表回答者见解不代表本站观点,请谨慎对待。

版权声明:作者保留权利,不代表本站立场。

回复

使用道具 举报

参与会员2

粗略的demo,定时器放在后面老衲一时想不通,此demo按顺序执行

var Lazing2 = function(name){    return {        _name : name,        _food : [],        _timeLimit : 0,        eat : function(food){            var _this = this;            setTimeout(function(){                console.log(_this._name,'吃',food)            },_this._timeLimit*1000);            return _this        },        delay : function(time){            var _this = this;            _this._timeLimit = time;            return _this;        }    }}Lazing2("老衲").eat('蛋糕').delay(3).eat('屎');
回复

使用道具 举报

总体思路就是 构造一个任务队列
class Lazing {  constructor(item = &#39;&#39;) {    this.queue = [{        key: &#39;init&#39;,        val() {          console.log(&#39;hello &#39; + item)        }      }]  }  eat(item) {    this.queue.push({      key: &#39;eat&#39;,      val() {        console.log(&#39;eating &#39; + item)      }    })    return this  }  sleep(time) {    this.queue.push({      key: &#39;sleep&#39;,      val: time * 1000    })    return this  }  sleepFirst(time) {    this.queue.unshift({      key: &#39;sleep&#39;,      val: time * 1000    })    return this  }  exec() {    for (let i = 0; i < this.queue.length; i++) {      let key = this.queue[&#39;key&#39;]      let val = this.queue[&#39;val&#39;]      if (key === &#39;sleep&#39;) {        this.queue.shift()        setTimeout(this.exec.bind(this), val)        break      } else {        val()        this.queue.shift()        i--      }    }  }}不过调用方式稍微不一样些,但能达到效果

new Lazing(&#39;Garry&#39;).exec()new Lazing(&#39;Garry&#39;).sleep(3).eat(&#39;rice&#39;).exec()new Lazing(&#39;Garry&#39;).eat(&#39;rice&#39;).eat(&#39;bread&#39;).exec()new Lazing(&#39;Garry&#39;).sleepFirst(3).eat(&#39;rice&#39;).exec()new Lazing(&#39;Garry&#39;).eat(&#39;rice&#39;).sleepFirst(3).exec()
回复

使用道具 举报

可能感兴趣的问答

发新帖
  • 微信访问
  • 手机APP