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 ~~~
學(xué)習(xí)是最好的投資!
我猜你要的是這個(gè) 下面展示一個(gè)原理 代碼結(jié)構(gòu)很簡(jiǎn)單
有一個(gè)執(zhí)行隊(duì)列jobs
調(diào)用before
的時(shí)候把內(nèi)容加到隊(duì)列頭部 調(diào)用getup
的時(shí)候把內(nèi)容加到尾部
基本原理就是利用setTimeout
時(shí)間設(shè)置為0 setTimeout
里面的函數(shù) 要在當(dāng)前運(yùn)行環(huán)境所有東西運(yùn)行完之后才會(huì)執(zhí)行
所以我在懷疑題主的第三個(gè)例子里 第三行又輸出一次噓噓
是不是筆誤
不過(guò)就算不是筆誤 也沒(méi)事 按照這個(gè)原理想怎么改就怎么改 多次調(diào)用也不是問(wèn)題
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;
}