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 Spring] Convertors
    [Java Spring] @InitBinder
    [Java Spring] Validations for Entity
    [Java JPA] @Query
    测试人员为什么要深入到项目实现中去
    有赞的深度需求功能测试
    youtube-dl 使用
    mysql update 的时候使用left join和where语句
    openstack 虚拟机设备管理器cpu核数与任务管理器不一致
    tcp扫描器实现原理
  • 原文地址:https://www.cnblogs.com/xiaomingge/p/12133708.html
Copyright © 2011-2022 走看看