download:全局视角零碎学习《举荐零碎》,实战中晋升竞争力
一道题目
看到一个很乏味的题目:实现一个办法,反对链式调用。
lazyman.lazy('Lisa').sleep(3).sleepFirst(4).eat('lunch');// 4s后输入:Sleep Afater 4// 输入:I'm Lisa// 3s后输入:Sleep After 3// 输入:I'm eat lunch解法话不多说,间接上代码:class LazyMan { callbacks = []; constructor() { this.next(); } next() { setTimeout(() => { const firstFn = this.callbacks.shift(); firstFn && firstFn(); }, 0); } lazy(name) { this.callbacks.push(() => { console.log(`Hi, I'm ${name}`); this.next(); }); return this; } sleep(time) { this.callbacks.push(() => { setTimeout(() => { console.log(`Sleep after ${time}`); this.next(); }, time * 1000); }); return this; } sleepFirst(time) { this.callbacks.unshift(() => { setTimeout(() => { console.log(`Sleep after ${time}`); this.next(); }, time * 1000); }); return this; } eat(item) { this.callbacks.push(() => { console.log(`I am eat ${item}`); this.next(); }); return this; }}const lazyman = new LazyMan();lazyman.lazy('Lisa').sleep(3).sleepFirst(4).eat('lunch');
题解剖析
这个题目,首先要知道如何实现链式调用,就是设置一个类,类中申明的办法的结尾最初都会从新返回该类实例的援用,这样就可能链式调用了。
所以咱们创立一个LazyMan
的类。
接下来是如何保障程序执行,那就是应用一个回调数组,每个函数调用后会查看一次回调是否为空,如果不为空,则继续执行。
同时为了保障第一次执行前,会先进行一遍所有函数的遍历,确认优先级,咱们在constructor
外面应用setTimeout
进行创立一个微工作,这样会等main函数里的宏工作全副执行完,才会开始真正的函数执行。