Heim  >  Fragen und Antworten  >  Hauptteil

javascript – Eine Interviewfrage, schauen Sie sich bitte um

Implementieren Sie eine Funktion wie diese

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

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

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


Fragen Sie: Was soll erreicht werden? ?
Der Interviewer sagte, dass es sich um Asynchronität, Warteschlange usw. handelt ~~~

PHPzPHPz2712 Tage vor485

Antworte allen(4)Ich werde antworten

  • 黄舟

    黄舟2017-05-16 13:32:09

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

    Antwort
    0
  • 仅有的幸福

    仅有的幸福2017-05-16 13:32:09

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

    有一个执行队列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;
    }

    Antwort
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-16 13:32:09

    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; 
    }

    Antwort
    0
  • 大家讲道理

    大家讲道理2017-05-16 13:32:09

    参考 promise 实现过程

    Antwort
    0
  • StornierenAntwort