高阶函数
基本概念
- 一个函数的参数是一个函数,可以称为高阶函数。(回调函数)
- 一个函数返回一个函数,也可以称之为高阶函数。(不单指闭包)
举个栗子
function coreFn() {
console.log('core fn');
}
const newFn = coreFn.before(() => {
console.log('before fn');
});
newFn();
Function.prototype.before = function (beforeFn) {
return () => {
beforeFn();
this();
}
}
Function.prototype.before = function (beforeFn) {
return (...args) => {
beforeFn();
this(...args);
}
}
function coreFn(a, b, c) {
console.log('core fn', a, b, c);
}
const newFn = coreFn.before(() => {
console.log('before fn');
});
newFn(1, 2, 3);
- 这里的before就是高阶函数,他接受一个函数作为参数,并且返回一个函数,在不修改原函数的情况下去做一些拓展功能,在平时的开发中会经常用到此类方案。