美文网首页
lazyman 实现

lazyman 实现

作者: heachou | 来源:发表于2017-04-07 16:00 被阅读0次

    <pre>
    function _lazyman(name) {
    this.tasks = [];
    var self = this;
    var fn = function() {
    console.log("hi this is " + name);
    self.next();
    }
    this.tasks.push(fn);
    setTimeout(function() {
    self.next();
    }, 0);
    }
    // 实现next
    _lazyman.prototype.next = function() {
    // body...
    var fn = this.tasks.shift();
    fn && fn();
    };
    _lazyman.prototype.eat = function(name) {
    // body...
    var self = this;
    var fn = function() {
    console.log("eat " + name + " ~");
    self.next();
    }
    this.tasks.push(fn);
    // 链式调用
    return this;
    };
    _lazyman.prototype.sleep = function(time) {
    // body...
    var self = this;
    var fn = function() {
    setTimeout(function() {
    console.log("sleep " + time + "s ~");
    self.next();
    }, time * 1000);
    }
    this.tasks.push(fn);
    // 链式调用
    return this;
    };
    _lazyman.prototype.sleepFirst = function(time) {
    // body...
    var self = this;
    var fn = function() {
    setTimeout(function() {
    console.log("sleepFirst " + time + "s ~");
    self.next();
    }, time * 1000);
    }
    // unshift
    this.tasks.unshift(fn);
    // 链式调用
    return this;
    };
    // 封装
    function LazyMan(name) {
    return new _lazyman(name);
    }
    </pre>
    调用:
    <code>
    <pre>
    LazyMan('hahah').eat('dinner').sleep(10).eat('lunch').sleepFirst(5);
    // sleepFirst 10s
    // hi this is hahah
    // eat dinner
    // sleep 10s
    // eat lunch
    </pre>
    </code>
    <p>1.实现链式调用</p>
    <p>2.实现流程控制,类似于express中的中间件概念</p>

    相关文章

      网友评论

          本文标题:lazyman 实现

          本文链接:https://www.haomeiwen.com/subject/ubmhattx.html