码迷,mamicode.com
首页 > 其他好文 > 详细

实现一个简单的lazyman

时间:2017-06-21 18:20:25      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:init   cond   var   bin   module   bsp   next   type   实现   

function lazyman(name) {
    return new lazyman.fn.init(name);
}

lazyman.fn = lazyman.prototype = {
    construct: lazyman,
    stack: null,
    status: 0,
    init: function (name) {
        this.name = name;
        this.stack = [];

        return this;
    },
    sleep: function (time) {
        var that = this;
        time = +time;
        if(time !== time) {
            this.next();
        } else if(this.status) {
            this.stack.unshift(this.sleep.bind(this, time));
        } else {
            this.status = 1;
            this.print(`sleeping ${time} seconds...`);

            setTimeout(function () {
                that.status = 0;
                that.next();
            }, time * 1000);
        }
        return this;
    },
    next: function () {
        while(this.status == 0 && this.stack.length) {
            this.print(
                this.stack.pop()()
            );
        }
        return this;
    },
    eat: function(thing) {
        this.stack.unshift(lazyEat.bind(null, this.name, thing));
        if(this.status == 0) {
            this.next();
        }
        return this;
    },
    print: console.log
}

lazyman.fn.init.prototype = lazyman.fn;

function lazyEat(name, thing) {
    return `${name} eat ${thing}`;
}

module.exports = lazyman;

 

实现一个简单的lazyman

标签:init   cond   var   bin   module   bsp   next   type   实现   

原文地址:http://www.cnblogs.com/dhsz/p/7060922.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!