javascript - An interview question, please take a look
PHPz
PHPz 2017-05-16 13:30:09
0
4
517

Implement this function

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

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

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


Ask what to use to achieve? ?
The interviewer said that it involves asynchronous, queue, etc.~~~

PHPz
PHPz

学习是最好的投资!

reply all(4)
黄舟

It is a process control, just like lazyMan, you can see this http://www.cnblogs.com/Upton/...

仅有的幸福

I guess what you want is this. Here is a principle. The code structure is very simple

When there is an execution queuejobs 调用before的时候把内容加到队列头部 调用getup, add the content to the end

The basic principle is to use the functions in setTimeout 时间设置为0 setTimeout to be executed after everything in the current operating environment has been run

So I’m wondering if the third line of the question’s third example is output again嘘嘘 Is it a typo

But even if it’s not a clerical error, it’s okay. According to this principle, you can change it however you want. It’s not a problem to call it multiple times

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

大家讲道理

Refer to the promise implementation process

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template