es5和es6实现lazyman

Posted -小白白白

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

ES6 模块串联

React/React Native 的ES5 ES6写法对照表

React/React Native 的ES5 ES6写法对照表

React/React Native 的ES5 ES6写法对照表

#yyds干货盘点#ES6转换成ES5

如何使用Babel将ES6转码为ES5?