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()

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

posted @ 2020-01-02 16:29  文艺范儿m  阅读(869)  评论(0编辑  收藏  举报