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

Lazyman功能实现

时间:2017-02-04 16:52:44      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:lazy   next   turn   调用   strong   链式   upper   ext   rip   

题目要求是这样的:

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

LazyMan(“Hank”).sleep(10).eat(“dinner”)输出
Hi! This is Hank!
//等待10秒..
Wake up after 10
Eat 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 5
Hi This is Hank!
Eat supper~

实现代码:

var task = [];
function next(){
if(task && task.length > 0) {
task.shift()();
}
}
function lazyMan(a) {
setTimeout(next, 0);
}

function LazyMan(a) {
task = [];
return new lazyMan().init(a);
}
lazyMan.prototype = {
init: function(a) {
var fn = function() {
console.log("Hi! This is " + a + "!");
next();
}
task.push(fn);
return this;
},
sleep: function(t) {
var fn = function() {
setTimeout(function() {
console.log("Wake up after " + t);
next();
}, t * 1000);
}
task.push(fn);
return this;
},
eat: function(d) {
var fn = function() {
console.log("Eat " + d + "~");
next();
}
task.push(fn);
return this;
},
sleepFirst: function(t) {
var fn = function() {
setTimeout(function() {
console.log("Wake up after " + t);
next();
}, t * 1000);
}
task.unshift(fn);
return this;
}

}

代码实现的思考:

1.JavaScript流程控制实现需要利用中间件原理;

2.JavaScript利用return this实现链式调用;

Lazyman功能实现

标签:lazy   next   turn   调用   strong   链式   upper   ext   rip   

原文地址:http://www.cnblogs.com/chyblog/p/6365047.html

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