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

es5和es6实现lazyman

时间:2017-01-20 16:25:17      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:封装   ret   const   style   class   struct   lazy   pre   es6   

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

标签:封装   ret   const   style   class   struct   lazy   pre   es6   

原文地址:http://www.cnblogs.com/bhan/p/6322915.html

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