首页 > 代码库 > es5和es6实现lazyman
es5和es6实现lazyman
es6实现
1 class _LazyMan { 2 constructor(name) { 3 this.tasks = []; 4 this.sleep = this.sleep.bind(this); 5 this.eat = this.eat.bind(this); 6 this.tasks.push(((name) => { 7 return () => { 8 console.log(‘Hi! This is ‘ + name + ‘!‘); 9 this.next(); 10 } 11 })(name)); 12 setTimeout(() => { 13 this.next(); 14 }, 0); 15 } 16 17 next() { 18 const fn = this.tasks.shift(); 19 fn && fn(); 20 } 21 eat(name) { 22 const fn = (() => { 23 return () => { 24 console.log(‘Eat ‘+ name +‘~‘); 25 this.next(); 26 } 27 })(name); 28 this.tasks.push(fn); 29 return this; 30 } 31 sleep(time) { 32 const fn = (() => { 33 return () => { 34 setTimeout(() => { 35 console.log(‘Wake up after ‘+ time +‘s!‘); 36 this.next(); 37 }, time * 1000); 38 } 39 })(time); 40 this.tasks.push(fn); 41 return this; 42 } 43 sleepFirst(time) { 44 const fn = () => { 45 setTimeout(() => { 46 console.log(‘Wake up after ‘+time+‘s!‘); 47 this.next(); 48 },time*1000); 49 } 50 this.tasks.unshift(fn); 51 return this; 52 } 53 } 54 55 const LazyMan = (name) => {return new _LazyMan(name)}
es5实现
1 function _LazyMan(name){ 2 this.tasks=[]; 3 var self=this; 4 var fn=(function(n){ 5 var name=n; 6 return function(){ 7 console.log(‘Hi! This is ‘+name+‘!‘); 8 self.next(); 9 } 10 })(name); 11 this.tasks.push(fn); 12 setTimeout(function(){ 13 self.next(); 14 },0); 15 } 16 17 _LazyMan.prototype.next=function(){ 18 var fn=this.tasks.shift(); 19 fn&&fn(); 20 } 21 _LazyMan.prototype.eat=function(name){ 22 var self=this; 23 var fn=(function(name){ 24 return function(){ 25 console.log(‘Eat ‘+name+‘~‘); 26 self.next(); 27 } 28 })(name); 29 this.tasks.push(fn); 30 return this; 31 } 32 _LazyMan.prototype.sleep=function(time){ 33 var self=this; 34 var fn=(function(time){ 35 return function(){ 36 setTimeout(function(){ 37 console.log(‘Wake up after ‘+time+‘s!‘); 38 self.next(); 39 },time*1000); 40 } 41 })(time); 42 this.tasks.push(fn); 43 return this; 44 } 45 _LazyMan.prototype.sleepFirst=function(time){ 46 var self=this; 47 var fn=(function(time){ 48 return function(){ 49 setTimeout(function(){ 50 console.log(‘Wake up after ‘+time+‘s!‘); 51 self.next(); 52 },time*1000); 53 } 54 })(time); 55 this.tasks.unshift(fn); 56 return this; 57 } 58 //封装 59 function LazyMan(name){ 60 return new _LazyMan(name); 61 }
es5和es6实现lazyman
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。