想要实现一个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' |
免责声明:本内容仅代表回答者见解不代表本站观点,请谨慎对待。
版权声明:作者保留权利,不代表本站立场。
|
|
|
|
|
|
|
粗略的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 = '') { 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['key'] let val = this.queue['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() |
|
|
|
|
|
|
|