es5和es6实现lazyman

es6实现
1 class _LazyMan {
constructor(name) {
this.tasks = [];
this.sleep = this.sleep.bind(this);
this.eat = this.eat.bind(this);
this.tasks.push(((name) => {
return () => {
console.log('Hi! This is ' + name + '!');
this.next();
}
})(name));
setTimeout(() => {
this.next();
}, 0);
} next() {
const fn = this.tasks.shift();
fn && fn();
}
eat(name) {
const fn = (() => {
return () => {
console.log('Eat '+ name +'~');
this.next();
}
})(name);
this.tasks.push(fn);
return this;
}
sleep(time) {
const fn = (() => {
return () => {
setTimeout(() => {
console.log('Wake up after '+ time +'s!');
this.next();
}, time * 1000);
}
})(time);
this.tasks.push(fn);
return this;
}
sleepFirst(time) {
const fn = () => {
setTimeout(() => {
console.log('Wake up after '+time+'s!');
this.next();
},time*1000);
}
this.tasks.unshift(fn);
return this;
}
} const LazyMan = (name) => {return new _LazyMan(name)}
es5实现
1 function _LazyMan(name){
this.tasks=[];
var self=this;
var fn=(function(n){
var name=n;
return function(){
console.log('Hi! This is '+name+'!');
self.next();
}
})(name);
this.tasks.push(fn);
setTimeout(function(){
self.next();
},0);
} _LazyMan.prototype.next=function(){
var fn=this.tasks.shift();
fn&&fn();
}
_LazyMan.prototype.eat=function(name){
var self=this;
var fn=(function(name){
return function(){
console.log('Eat '+name+'~');
self.next();
}
})(name);
this.tasks.push(fn);
return this;
}
_LazyMan.prototype.sleep=function(time){
var self=this;
var fn=(function(time){
return function(){
setTimeout(function(){
console.log('Wake up after '+time+'s!');
self.next();
},time*1000);
}
})(time);
this.tasks.push(fn);
return this;
}
_LazyMan.prototype.sleepFirst=function(time){
var self=this;
var fn=(function(time){
return function(){
setTimeout(function(){
console.log('Wake up after '+time+'s!');
self.next();
},time*1000);
}
})(time);
this.tasks.unshift(fn);
return this;
}
//封装
function LazyMan(name){
return new _LazyMan(name);
}
上一篇:tcp 服务端如何判断客户端断开连接


下一篇:ThinkPhp_5框架开发【指导】