javascript - 一道面试题,大家看过来
PHPz
PHPz 2017-05-16 13:30:09
[HTML讨论组]

实现这样子的函数

person('tom')
// 输出 hi tom

person('tom').getup('洗刷刷')
// 输出 hi tom
// 输出 tom getup and 洗刷刷

person('tom').before('嘘嘘').getup('洗刷刷')
// 输出 tom 嘘嘘
// 输出 hi tom 
// 输出 tom 嘘嘘 getup and 洗刷刷


问 用什么来实现??
面试官说,涉及到异步,队列什么的~~~

PHPz
PHPz

学习是最好的投资!

全部回复(4)
黄舟

就是一个流程控制啊,就像lazyMan,可以看这个http://www.cnblogs.com/Upton/...

仅有的幸福

我猜你要的是这个 下面展示一个原理 代码结构很简单

有一个执行队列jobs 调用before的时候把内容加到队列头部 调用getup的时候把内容加到尾部

基本原理就是利用setTimeout 时间设置为0 setTimeout里面的函数 要在当前运行环境所有东西运行完之后才会执行

所以我在怀疑题主的第三个例子里 第三行又输出一次嘘嘘 是不是笔误

不过就算不是笔误 也没事 按照这个原理想怎么改就怎么改 多次调用也不是问题

function person(name){
    var self = {};
    self.jobs = ["hi " + name];
    self.before = function(s){
        self.jobs.unshift(name + " " + s);
        return this;
    }
    self.getup = function (s){
        self.jobs.push("getup and " + s);
        return this;
    }
    setTimeout(function(){console.log(self.jobs)}, 0)
    return self;
}

给我你的怀抱
function person(name){
    setTimeout(() => console.log(`hi ${name}`)); 

    this.name = name; 

    this.before = before_todo => {
        this.before_todo = before_todo; 
        console.log(`${this.name} ${before_todo}`); 
        return this; 
    }

    this.getup = getup_todo => {
        setTimeout(() => {
            var str = this.name; 
            if (this.before_todo) str += ' ' + this.before_todo; 
            str += (' getup and ' + getup_todo); 
            console.log(str); 
        }); 

        return this; 
    }

    return this; 
}

大家讲道理

参考 promise 实现过程

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号