什么是高阶函数
高阶函数:是指一个函数他的参数是函数 / 返回值是函数
let is = false;
function isType(param, type) {
return Object.prototype.toString.call(param).includes(type);
}
console.log(isType(is,"Boolean"));
console.log(isType(is,"String"));
//封装一个高阶函数
function isType(type) {
return function (param) {
return Object.prototype.toString.call(param).includes(type);
};
}
let types = ["String","Number", "Boolean","Object","Array","Null","Undefined"];
let utils = {};
types.forEach(type=>{
utils["is" + type] = isType(type);
})
console.log(utils);
console.log(utils.isString("1"));
console.log(utils.isNumber(1));
console.log(utils.isNull(null));
console.log(utils.isNull(undefined));
console.log(utils.isUndefined(undefined));
console.log(utils.isArray([]));
可以用来做什么?
1、预置参数 (如 bind)
bind函数也是返回一个自定义了this的新函数
2、解决异步问题 (异步并发问题解决 计数就好),Promise.all 的原理
let fs = require("fs");
let contentArr = [];
function callback(content) {
contentArr.push(content);
if(contentArr.length == 2){
console.log(contentArr.join("=>"));
}
}
fs.readFile("./hello.txt","utf8",function (err,content) {
callback(content);
})
fs.readFile("./world.txt","utf8",function (err,content) {
callback(content);
})
// world =>hello
// 保证顺序
let fs = require("fs");
let contentArr = [];
let count = 0;
function callback(content,index) {
contentArr[index] = content;
if (++count == 2) {
console.log(contentArr.join("=>"));
}
}
fs.readFile("./hello.txt","utf8",function (err,content) {
callback(content,0);
})
fs.readFile("./world.txt","utf8",function (err,content) {
callback(content,1);
})
//高阶函数改写
let fs = require("fs");
/**
* 高阶函数 当函数执行 times N 次后才执行回调
*/
function after(times,callback) {
let arr = [];
return function (content) {
arr.push(content);
if(--times === 0){
callback(arr);
}
};
}
//当三个异步读取文件的操作都完成之后才执行回调 三个是串行的
let afterInstence = after(3,function (params) {
console.log(params);
})
fs.readFile("./hello.txt","utf8",function (err,content) {
afterInstence(content);
})
fs.readFile("./wonderful.txt", "utf8", function (err, content) {
afterInstence(content);
});
fs.readFile("./world.txt","utf8",function (err,content) {
afterInstence(content);
})
3、AOP 面向切片编程 (扩展原有方法,不影响原有功能,加上自己自定义的东西 / 或重写原方法)【待研究】
//握手之前先擦擦手
function sharkHands(what) {
console.log(what);
}
Function.prototype.before = function (fn) {
let that = this;
return function () {
fn();
that(...arguments);
}
}
let sharkHandsFn = sharkHands.before(function () {
console.log("擦了擦手");
});
sharkHandsFn("=》握手");
网友评论