zoukankan      html  css  js  c++  java
  • js链式调用原理

    将执行函数放入数组队列,使用next() 执行,将调用函数赋值给构造函数的原型,可以进行连续链式调用,必要:执行功能函数需要返回this

         let index = 0;
            let stack = [];
    
            function next() {
                let fn = stack[index];
                index++;
                if (typeof fn === 'function') {
                    fn();
                }
            }
    
            function Man(name) {
                stack.push(function () {
                    console.log("Hi! This is " + name);
                    next();
                })
            }
            var Person = function (name) {
                return new Man(name)
            }
            Man.prototype.sleep = function (time) {
                stack.push(function () {
                    setTimeout(function () {
                        console.log("Wake up after " + time)
                        next()
                    }, time * 1000)
                })
                return this;
            }
            Man.prototype.eat = function (food) {
                stack.push(function () {
                    console.log('Eat ' + food)
                    next();
                })
                return this;
            }
            Man.prototype.sleepFirst = function (time) {
                stack.unshift(function () {
                    setTimeout(function () {
                        console.log('wake up after ' + time)
                        next()
                    }, time * 1000)
                })
                return this;
            }
            // Person('Li')
            /* 输出:
            Hi! This is Hank!
            */
            // Person('Dan').sleep(3).eat('dinner')
            /* 输出:
            Hi! This is Hank!
            // 等待10秒..
            Wake up after 10
            Eat dinner~
            */
            // Person('Jerry').eat('dinner~').eat('supper~')
            /* 输出:
            Hi This is Hank!
            Eat dinner~
            Eat supper~
            */
            Person('Smith').sleepFirst(2).eat('supper')
            /* 等待5秒,输出
            Wake up after 5
            Hi This is Hank!
            Eat supper
            */
            next()

    备注:次代码段摘抄网上经典面试题

  • 相关阅读:
    JAVA中循环删除list中元素的方法总结
    弹力设计总结
    CPU飚高问题排查基本步骤
    缓存数据库更新策略
    .Module高内聚低耦合的思考
    javascript回调函数及推论
    Laravel Autoloader模块分析
    Laravel Event模块分析
    数据操作分层设计
    Discuzx2开发标准流程
  • 原文地址:https://www.cnblogs.com/xiaomingge/p/12133708.html
Copyright © 2011-2022 走看看