<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>
网友评论