javascript
const log = console.log;
function m1(next) { log(1); next(); log(2); }
function m2(next) { log(3); next(); log(4); }
function m3(next) { log(5); next(); log(6); }
function end() { log('end'); }
function m3_end() { m3(end); }
function m2_end() { m2(m3_end); }
m1(m2_end);
// 打印顺序 1 3 5 end 6 4 2
利用高阶函数
fn => compose();
高阶函数:
- 入口参数是函数;
- 返回函数;
- 两者皆备;
javascript
const log = console.log;
function m1(next) { log(1); next(); log(2); }
function m2(next) { log(3); next(); log(4); }
function m3(next) { log(5); next(); log(6); }
let ms = [];
use(m1); use(m2); use(m3);
function use(mx) {
ms.push(mx);
}
let index = 0;
function compose(index = 0) {
if (index === ms.length) {
return () => { log('end') };
}
return () => {
ms[index](compose(index + 1));
};
}
let fn = compose();
fn();