亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

想要實現一個class Lazing 函數,輸出如下該怎么寫?

想要實現一個class Lazing 函數,輸出如下該怎么寫?

慕神8447489 2018-07-13 11:07:17
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 回答

?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

粗略的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('屎');


查看完整回答
反對 回復 2018-07-15
?
三國紛爭

TA貢獻1804條經驗 獲得超7個贊

總體思路就是 構造一個任務隊列

class Lazing {  constructor(item = '') {    this.queue = [{
        key: 'init',        val() {
          console.log('hello ' + item)
        }
      }]
  }

  eat(item) {    this.queue.push({
      key: 'eat',      val() {
        console.log('eating ' + item)
      }
    })    return this
  }

  sleep(time) {    this.queue.push({
      key: 'sleep',      val: time * 1000
    })    return this
  }

  sleepFirst(time) {    this.queue.unshift({
      key: 'sleep',      val: time * 1000
    })    return this
  }

  exec() {    for (let i = 0; i < this.queue.length; i++) {
      let key = this.queue[i]['key']
      let val = this.queue[i]['val']      if (key === 'sleep') {        this.queue.shift()
        setTimeout(this.exec.bind(this), val)        break
      } else {        val()        this.queue.shift()
        i--
      }
    }
  }
}

不過調用方式稍微不一樣些,但能達到效果

new Lazing('Garry').exec()new Lazing('Garry').sleep(3).eat('rice').exec()new Lazing('Garry').eat('rice').eat('bread').exec()new Lazing('Garry').sleepFirst(3).eat('rice').exec()new Lazing('Garry').eat('rice').sleepFirst(3).exec()


查看完整回答
反對 回復 2018-07-15
  • 2 回答
  • 0 關注
  • 487 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號