What is a callback function

detailed

A callback function is a function called through a function pointer. Pass a pointer to a function (memory address) as an argument to another function. When the pointer is used to call the function it points to, the function it points to is the callback function. A callback function is not called directly by the implementers of the function, but is called by another party when a particular event or condition occurs in response to that event or condition. (Excerpt from Baidu Baike)

understand

Js function is also an object, the function stored in == memory address == as an argument to another function, when this address is called to the function, is the callback function.

A brief

A function that is passed as an argument to a function is a callback function

What is a higher-order function

A higher-order function is a function that takes a function as an argument or returns a function as output

A few lines of code understand callbacks and higher orders

function fun(val) {
   console.log(val)
};

function fn(callback) {
   let num = 10;
   callback(num);
};

fn(fun);
Copy the code

The code output is 10, and here are the detailed steps I understand to execute

  1. Call fn with fun
  2. The fn function is executed with callback as the function parameter
  3. Declare a variable num and assign it to 10
  4. Call the callback function fun with num of 10
  5. The fun callback is executed, the argument num is received and printed, so the result is 10

conclusion

The callback function

The code above is called fun as an argument to fn and according to the definition of a callback function == the function passed as an argument to the function is the callback function == so fun is the callback function

Higher-order functions

The above code is fn and the argument to fn is fun and according to the definition of higher order function == the function that receives the argument is higher order function == so fn is higher order function

The closure function

Why even mention closures?


This is not allowed in the js scope chain. == only closures can break the scope chain and pass variables and methods inside the function to the outside, so that external functions can access variables and methods inside the function. ==, but the callback is also called, so the callback is also a closure