zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    最大子数组问题(分治策略实现)
    Solving the Detached Many-to-Many Problem with the Entity Framework
    Working With Entity Framework Detached Objects
    Attaching detached POCO to EF DbContext
    如何获取qq空间最近访问人列表
    Health Monitoring in ASP.NET 2.0
    problem with displaying the markers on Google maps
    WebMatrix Database.Open… Close() and Dispose()
    Accessing and Updating Data in ASP.NET: Retrieving XML Data with XmlDataSource Control
    Create web setup project that has crystal reports and sql script run manually on client system
  • 原文地址:https://www.cnblogs.com/bhan/p/6322915.html
Copyright © 2011-2022 走看看