1. 程式人生 > >js實現lazyman(流程控制)

js實現lazyman(流程控制)

function _lazyMan(name) {
    this.name = name;
    this.task = [];
    this.default();
    var _this = this;
    setTimeout(function() {
        _this.next();
    }, 0)


}
_lazyMan.prototype.next = function() {
    var fn = this.task.shift();
    fn && fn();
}
_lazyMan.prototype.default = function
() {
var _this = this; var fn = (function(name) { return function() { console.log("Hi!This is " + name); _this.next(); } })(this.name); this.task.push(fn); return this; } _lazyMan.prototype.sleep = function(num) { var _this = this; var
fn = (function() { return function() { setTimeout(function() { console.log("wait after" + num); _this.next(); }, num * 1000) } })(); this.task.push(fn); return this; } _lazyMan.prototype.sleepFirst = function(num) { var
_this = this; var fn = (function() { return function() { setTimeout(function() { console.log("Wait first after " + num) _this.next(); }, num * 1000) } })(); this.task.unshift(fn); return this; } _lazyMan.prototype.eat = function(some) { var _this = this; var fn = (function() { return function() { console.log("Eating " + some); } })(); this.task.push(fn); return this; } function LazyMan(name) { return new _lazyMan(name); } var a = LazyMan("hank").sleep(2).eat("some").sleepFirst(1);