實現一個LazyPig,可以按照以下方式調用:
/* LazyPig(“Peggy”)輸出:
Hello,I’m Peggy!
LazyPig("Peggy").sleep(10).eat("dinner")輸出
Hello,I'm Peggy!
//等待10秒..
Wake up after 10
Eat dinner~
LazyPig("Peggy").eat("dinner").eat("supper")輸出
Hello,I'm Peggy!
Eat dinner~
Eat supper~
以此類推。
*/
//最開始:
function LazyPig(name){
return new Lazy(name)
}
function Lazy(name){
this.name = name;
console.log('Hi, 我是' + name)
}
Lazy.prototype = {
eat: function(smt){
console.log(this.name + ' is eating ' + smt)
return this
},
sleep: function(time){
setTimeout(()=>{
console.log(this.name + ' wake up !')
}, time * 1000)
return this;
}
}
LazyPig('哼哼').eat('dinner').sleep(5)
發現有點不合題意,如果eat在sleep之後調用,也是緊跟着name直接log出來了,應該在sleep 5s之後 跟在sleep之後
function LazyPig(name){
return new Lazy(name)
}
function Lazy(name){
this.name = name;
this.task = [];
console.log('Hi, 我是' + name)
let _this = this;
let fn = (function(){
return function(){
_this.next()
}
})()
this.task.push(fn)
setTimeout(()=>{
_this.next()
},0)
}
Lazy.prototype = {
next: function(){
var fn = this.task.shift()
fn && fn()
},
sleep: function(time){
let _this = this;
let fn = (function(time){
return function(){
setTimeout(()=>{
console.log(_this.name + ' Wake up !')
_this.next()
}, time * 1000)
}
})(time)
this.task.push(fn)
return this;
},
eat: function(smt){
let _this = this;
let fn = (function(smt){
return function(){
console.log(_this.name + ' is eating ' + smt);
_this.next()
}
})(smt)
this.task.push(fn)
return this;
}
}
LazyPig('哼哼').sleep(5).eat('早飯')