实现一个LazyMan,可以按照以下方式调用:
LazyMan("Hank")输出:
Hi! This is Hank!
LazyMan("Hank").sleep(10).eat("dinner")输出
Hi! This is Hank!
//等待10秒..
Wake up after 10
Eat dinner~
LazyMan("Hank").eat("dinner").eat("supper")输出
Hi This is Hank!
Eat dinner~
Eat supper~
LazyMan("Hank").sleepFirst(5).eat("supper")输出
//等待5秒
Wake up after 5
Hi This is Hank!
Eat supper
以此类推。
function LazyMan(name){
return new _lazyman(name)
}
function _lazyman(name){
this.tasks = [];
var that = this;
var fn = (function(name){
return function(){
console.log("Hello I am " + name)
that.next()
}
})(name)
this.tasks.push(fn);
setTimeout(function(){
that.next()
},0)
}
_lazyman.prototype ={
constructor:_lazyman,
next:function(){
var fn = this.tasks.shift()
fn && fn()
},
sleep:function(time){
var that = this;
var fn = (function(time){
return function() {
console.log("sleep ..." +time)
setTimeout(function(){
that.next()
},time)
}
})(time)
this.tasks.push(fn);
return this;
},
sleepfirst:function(time){
var that = this;
var fn = (function(time){
return function(){
console.log("sleep ..." +time)
setTimeout(function(){
that.next()
},time)
}
})(time)
this.tasks.unshift(fn)
return this;
},
eat:function(something){
var that = this;
var fn = (function(something){
return function(){
console.log("Eat " + something);
that.next()
}
})(something)
this.tasks.push(fn)
return this;
}
}
LazyMan("Joe").sleepfirst(5000).eat("breakfast").sleep(3000).eat("dinner").sleep(3000).eat("supper");
网友评论