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 回答
慕姐4208626
TA贡献1852条经验 获得超7个赞
粗略的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('屎');
qq_笑_17
TA贡献1818条经验 获得超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()添加回答
举报
0/150
提交
取消
