Higher-order function and closure (Closure) | Functional programming

hi~ I am 无言非影, very happy to share my learning journey here. Some notes compiled
about functional programming are all recorded in: Functional Programming Column


What are higher-order functions?

In JavaScript, a function can receive another function as a parameter or return a function as output. This function is called a higher-order function .

  • Higher-order functions can operate on other functions:
    1. as other functions参数
    2. as other functions返回结果

Used as parameters of other functions

Example: Mock Array.prototype.map()

The Array.prototype.map() method creates a new array, the result of which is that each element in the array is the return value of a call to the provided function.

 let array = [1,2,3,4,5] // 数字组成的数组
 const square = item=>item ** 2 // 回调函数,进行求2次幂运算
 const newArr = array.map(square) // 使用map对数组内数据进行计算
 console.log(newArr); // 打印结果: [ 1, 4, 9, 16, 25 ]

When we call array.map(square), the parameter squareis a callback function. The callback function is used as a parameter of the map function, and the data is processed to the power of 2, and finally a new array is returned.

We can simulate map()the method:

  let array = [1,2,3,4,5] // 数字组成的数组

  // array:原数组 fn: 回调函数
  const map = (array, fn) => {
    
     
    let results = [] 

    // 遍历原数组
    for (const value of array) {
    
     
        results.push(fn(value)) // 对数据中的每一项先通过回调函数 fn()进行处理,之后再放到新数组 results 中
    }
    return results // 返回一个新数组
  }
  const newArr = map(array, v => v ** 2)
  console.log(newArr) // 打印结果: [ 1, 4, 9, 16, 25 ]

Used as the return result of other functions

In addition to accepting functions as parameters, higher-order functions can also return functions as result values.

// 一个函数返回另一个函数
function sum (arr) {
    
    
    let msg = 'Hi~ wuyanfeiying' 
    return function () {
    
     
        console.log(msg) 
    } 
}

// 第一种调用方式
const fn = sayHi() 
fn() //Hi~ wuyanfeiying

// 第二种调用方式
sayHi()()//Hi~ wuyanfeiying

In the above function, a function is returned, and the members inside the original function are also accessed in the function, so it can be called 闭包.

Closure

Closure: References to a function and its surrounding state (lexical environment) are bundled together to form a closure. The internal function of a function can be called in another scope and the members in the function scope can be accessed.

The above example (used as the return result of other functions) is actually one 闭包,

// 求一个数的二次方
function makePower (power) {
    
    
  return function (number) {
    
    
    return Math.pow(number, power)
  }
}

// 求平方
let power2 = makePower(2) // 此时返回的是一个函数

// 被调用时才执行
console.log(power2(4)) // 16
console.log(power2(5)) // 25

Each call returns a new function , even if the same parameters are passed in:

// 求平方
// 创建两个新函数:
let power2_1 = makePower(2)
let power2_2 = makePower(2)
power2_1 === power2_2 // false

power2_1()The calling resultspower2_2() of and have no influence on each other .

The role of closure

Extend the scope of internal members of a function

  1. It is a function that can read the internal variables of other functions. It is essentially the parsing process of variables (from the inside out).

When the function is executed, it is on the execution stack. After execution, it is removed from the execution stack and the memory of the internal members is released. However, after the function is executed and removed, when the memory is released, if there is an external reference, the memory of the internal member cannot be released.

  1. Can be used to encapsulate private variables and implement simulation

  2. Variables can be saved to memory

The significance of using higher-order functions

  • Reduces code length, increases readability and simplifies accessibility.
  • High-order functions are used to abstract common problems, and there is no need to consider how they are implemented internally when they are called.

appendix

Guess you like

Origin blog.csdn.net/weixin_40887836/article/details/118500734