最近被问到这样一个问题,如下:
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
博客迁移新地址:点击前往
大前端知识库收集分享 www.190tech.site 壹玖零Tech
搜罗各种前后端奇淫技巧,花式编程思想,日日更新,速来围观吧...
网友评论