欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

高阶函数

程序员文章站 2022-04-01 18:41:22
...

高阶函数:英文叫Higher-order function。JavaScript的函数其实都指向某个变量。既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。

function say(a){
    console.log('say',a)
}
Function.prototype.before=function(callback){
    return (...args)=>{
        callback()
        this(...args)
    }
}
let beforeSay= say.before(function(){
    console.log('before say')
})
beforeSay("aaa")
//before say
//say aaa
function add(x, y, f) {
    return f(x) + f(y);
}
//当调用add(-5, 6, Math.abs)时,参数x,y和f分别接收-5,6和函数Math.abs,根据函数定义,可以推导计算过程为:
//x = -5;
//y = 6;
//f = Math.abs;
//f(x) + f(y) ==> Math.abs(-5) + Math.abs(6) ==> 11;
//return 11;

//用代码验证一下:
add(-5, 6, Math.abs); // 11
相关标签: start again