[JavaScript] A brief introduction to callbacks, anonymous and recursive functions

Callback Functions: In JavaScript, callback functions are functions that are passed as parameters to other functions. When an operation is completed, the main function calls the callback function to process the results. This mechanism is often used in asynchronous programming, such as handling AJAX requests or timer events.

Here is a simple example where a callback function is used to handle the results of an asynchronous request:

function fetchData(callback) {
  // 模拟异步请求
  setTimeout(function() {
    const data = '这是从服务器获取的数据';
    callback(data); // 调用回调函数处理数据
  }, 2000);
}

function processData(data) {
  console.log('处理数据:', data);
}

fetchData(processData); // 将回调函数传递给fetchData函数

Anonymous Functions: Anonymous functions are functions without names and can be defined and used directly. Usually as a callback function, an immediately executed function, or a function in a function expression.

Here is an example of using an anonymous function as a callback function:

setTimeout(function() {
  console.log('2秒后执行的匿名函数');
}, 2000);

Anonymous functions can also be used by assigning to variables or as immediately executed functions:

const greet = function(name) {
  console.log('Hello', name);
};

greet('Alice'); // 输出: Hello Alice

// 立即执行函数
(function() {
  console.log('这是一个立即执行函数');
})();

 Recursive Functions: A recursive function is a function that calls itself within the function body. In this way, a function can perform the same operation repeatedly until a specific condition is met.

Here is an example of a recursive function that computes factorial:

function factorial(n) {
  if (n === 0) {
    return 1; // 基准条件
  } else {
    return n * factorial(n - 1); // 递归调用
  }
}

console.log(factorial(5)); // 输出:120

Recursive functions need to pay attention to setting the baseline condition (stopping recursion) to avoid infinite loops, and ensure that each recursive call moves closer to the baseline condition.

Guess you like

Origin blog.csdn.net/wuzhangting/article/details/132446709