首页 > 网站 > WEB开发 > 正文

LazyMan

2024-04-27 15:03:26
字体:
来源:转载
供稿:网友

参考:http://web.jobbole.com/89626/

题目:

实现一个LazyMan,可以按照以下方式调用:LazyMan(“Hank”)输出:Hi! This is Hank!

LazyMan(“Hank”).sleep(10).eat(“dinner”)输出Hi! This is Hank!//等待10秒..Wake up after 10Eat dinner~

LazyMan(“Hank”).eat(“dinner”).eat(“supper”)输出Hi This is Hank!Eat dinner~Eat supper~

LazyMan(“Hank”).sleepFirst(5).eat(“supper”)输出//等待5秒Wake up after 5Hi This is Hank!Eat supper

以此类推。

思路

关键是输出的顺序,以及需要在每一个任务执行完再执行下一步,类似PRomise,使用队列也可以。链式调用则要求每个方法都得返回当前对象。

代码

var LazyMan = function(name) {    if (!(this instanceof LazyMan)) {        return new LazyMan(name);    }    this.quene = [];    var self = this;    var fn = function() {        console.log('Hi! This is ' + name);        self.next();    };    this.quene.push(fn);    setTimeout(function() {        self.next();    }, 0);}LazyMan.prototype = {    next: function() {        if (this.quene.length) {            var fn = this.quene.shift();            if ((typeof fn).toLowerCase() === 'function') {                fn();            }        }    },    sleep: function(time) {        var self = this;        var fn = function() {            setTimeout(function() {                console.log('Wake up after ' + time);                self.next();            }, time * 1000);        };        this.quene.push(fn);        return this;    },    sleepFirst: function(time) {        var self = this;        var fn = function() {            setTimeout(function() {                console.log('Wake up after ' + time);                self.next();            }, time * 1000);        };        this.quene.unshift(fn);        return this;    },    eat: function(food) {        var self = this;        var fn = function() {            console.log('Eat ' + food + '~');            self.next();        };        this.quene.push(fn);        return this;    }};


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表