zoukankan      html  css  js  c++  java
  • js实现队列-通过闭包方式

    需求:

    // 实现一个LazyMan,可以按照以下方式调用:
    LazyMan(“Hank”)
    /* 输出: 
    Hi! This is Hank!
    */
    
    LazyMan(“Hank”).sleep(10).eat(“dinner”)输出
    /* 输出: 
    Hi! This is Hank!
    // 等待10秒..
    Wake up after 10
    Eat dinner~
    */
    
    LazyMan(“Hank”).eat(“dinner”).eat(“supper”)
    /* 输出: 
    Hi This is Hank!
    Eat dinner~
    Eat supper~
    */
    
    LazyMan(“Hank”).sleepFirst(5).eat(“supper”)
    /* 等待5秒,输出
    Wake up after 5
    Hi This is Hank!
    Eat supper
    */
    
    // 以此类推。

    实现:

    var LazyMan = function(name) {  
        var queue = [];
        var sayHi = function() {
          console.log('Hi! This is ' + name + '!');
          self.next();
        }
        queue.push(sayHi);
        setTimeout(function(){
          self.next();
        }, 0);
        var self = {
          next: function() {
            if (queue.length) {
              var fn = queue.shift();
              if (typeof fn === 'function') {
                fn();
              }
            }
          },
          sleep: function(time) {
            queue.push(function() {
              setTimeout(function() {
                console.log('Wake up after ' + time);
                self.next();
              }, time * 1000);
            });
            return this;
          },
          eat: function(meal) {
            queue.push(function() {
              console.log('Eat ' + meal + '~');
              self.next();
            });
            return this;
          },
          sleepFirst: function(time) {
            queue.unshift(function() {
              setTimeout(function() {
                console.log('Wake up after ' + time);
                self.next();
              }, time * 1000);
            });
            return this;
          },
        }
        return self;
    }

    分析:

    待完成...

  • 相关阅读:
    Java学习笔记8(面向对象3:接口)
    面向对象2(继承,抽象类)
    java学习笔记6(面向对象1:概念,private)
    排序方法-循环和数组练习
    ArrayList方法综合练习
    Eclipse的配置
    集合(ArrayList)简述
    java学习笔记5(方法)
    数据结构9——最小生成树
    数据结构8——图的遍历
  • 原文地址:https://www.cnblogs.com/fanfan-code/p/6398467.html
Copyright © 2011-2022 走看看