高阶函数: 函数参数如果是函数,或者这个函数返回一个新的函数
1. 高阶函数与AOP
AOP(面相切面编程): 主要作用是把一些跟核心业务逻辑模块无关的功能抽离出来。
例如:日志统计,异常处理等。把这些功能抽离出来后,通过"动态植入"的方法,掺入到业务逻辑模块中。这样做的好处是保证业务逻辑模块的纯净和高内聚,其次可以方便的复用日志统计等功能模块
1.1 before(前置通知)
function say(who) {
console.log(who + 'hello');
}
Function.prototype.before = function(beforeFunc) {
// this 箭头函数中没有this 也没有arguments
return (...args) => { // ['我']
beforeFunc();
this(...args);
}
}
// beforeSay 是一个包装后的函数
let beforeSay = say.before(() => {
console.log('开始说话')
})
beforeSay('我');
// 结果:
// 开始说话
// 我hello
1.2 after(后置通知)
function say(who) {
console.log(who + 'hello');
}
Function.prototype.after = function(afterFunc) {
return (...args) => { // ['我']
this(...args);
afterFunc();
}
}
say = say.after(() => {
console.log('结束说话')
})
say('我');
// 结果:
// 我hello
// 结束说话
2. react 事务
React内部的事务分为三个阶段initialize,method 以及close 阶段,会在开始和结束时候分别遍历transactionWrapper内部的所有初始化方法和close方法。
class Transaction{
perform(anyMethod,wrappers){
wrappers.forEach(wraper=>wraper.initialize())
anyMethod();
wrappers.forEach(wraper=>wraper.close())
}
}
let transaction = new Transaction();
let oldFunc = ()=>{
console.log('原有的逻辑')
}
transaction.perform(oldFunc,[{ // warpper
initialize(){
console.log('初始化1')
},
close(){
console.log('关闭1')
}
},{ // warpper
initialize(){
console.log('初始化2')
},
close(){
console.log('关闭2')
}
}]);
// 结果:
// 初始化1
// 初始化2
// 原有的逻辑
// 关闭1
// 关闭2
3. 判断复杂数据类型
// 判断数据类型
// typeof instanceof contructor Object.prototype.toString.call
function isType(type){ // 变量
return function(content){
return Object.prototype.toString.call(content) === "[object "+type+"]";
}
}
// isString isArray isBoolean
let types = ['String','Boolean','Number','Null','Undefined'];
let utils = {}; // 工具库
for(let i = 0 ; i< types.length;i++){
let type = types[i]
utils['is'+type] = isType(type);
// utils.isString = function 预制参数 和 bind一样
}
let flag = utils.isString('hello');
console.log(flag);
4. 柯里化
将以下函数柯里化
function fn(a,b,c){
return a+b+c;
}
function currying(fn) {
let arr = [];
// 参数 fn 及 return 语句之前定义的变量都被保存下来了
let next = (...args) => {
if (args.length > 0) {
arr.push(...args);
return next;
} else {
return fn(arr);
}
}
return next;
// ES5 写法
// return function() {
// if (arguments.length === 0) {
// return fn.call(null, arr);
// } else {
// arr = arr.concat([].slice.call(arguments));
// }
// }
}
let add = currying((args) => {
let sum = 0;
for (let item of args) {
sum += item;
}
return sum;
})
add(1);
add(2, 3);
add(4);
let sum = add(5)();
console.log(sum); // 15
柯里化与反柯里化可参考 浅析函数柯里化与反柯里化。