标签: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实现链式调用;
标签:lazy next turn 调用 strong 链式 upper ext rip
原文地址:http://www.cnblogs.com/chyblog/p/6365047.html