实现一个LazyMan

2017-01-22  本文已影响33人  wengjq
function _lazyMan(name) {
  this.tasks = [];   
  var _this = this;
  var fn =(function(n){
    var name = n;
    return function(){
      console.log("Hi! This is " + name + "!");
      _this.next();
    }
  })(name);
  this.tasks.push(fn);
  setTimeout(function(){
    _this.next();
  }, 0); 
}
_lazyMan.prototype.next = function() { 
  var fn = this.tasks.shift();
  fn && fn();
}
_lazyMan.prototype.eat = function(name) {
  var _this = this;
  var fn =(function(name){
    return function(){
       console.log("Eat " + name + "!");
       _this.next();
    }
  })(name);
  this.tasks.push(fn);
  return this; 
}
_lazyMan.prototype.sleep = function(time) {
  var _this = this;
  var fn = (function(time){
    return function() {
        setTimeout(function(){
           console.log("Wake up after " + time + "s!");
           _this.next();
        }, time * 1000);
    }
  })(time);
  this.tasks.push(fn);
  return this;
}
function lazyMan(name){
  return new _lazyMan(name);
}
上一篇 下一篇

猜你喜欢

热点阅读