返回

JS-回调函数的写法

前端

回调函数的定义

回调函数:当一个函数要实现某个功能时,将另一个功能函数作为参数传入,这样的功能函数叫回调函数。

回调函数的写法

function callbackFunction() {
  // code to be executed
}

传入无参的回调函数

如果要传入无参的回调函数,则可以使用以下语法:

function mainFunction(callback) {
  // code to be executed before calling the callback function
  callback();
  // code to be executed after calling the callback function
}

mainFunction(function() {
  // code to be executed in the callback function
});

传入确定参数的回调函数

如果要传入确定参数的回调函数,则可以使用以下语法:

function mainFunction(callback, arg1, arg2, ...) {
  // code to be executed before calling the callback function
  callback(arg1, arg2, ...);
  // code to be executed after calling the callback function
}

mainFunction(function(arg1, arg2, ...) {
  // code to be executed in the callback function
}, arg1, arg2, ...);

传入不定参数的回调函数

如果要传入不定参数的回调函数,则可以使用以下语法:

function mainFunction(callback, ...args) {
  // code to be executed before calling the callback function
  callback(...args);
  // code to be executed after calling the callback function
}

mainFunction(function(...args) {
  // code to be executed in the callback function
}, arg1, arg2, ...);

传入不定参数的回调函数

如果要传入不定参数的回调函数,则可以使用以下语法:

function mainFunction(...args, callback) {
  // code to be executed before calling the callback function
  callback(...args);
  // code to be executed after calling the callback function
}

mainFunction(arg1, arg2, ..., function(...args) {
  // code to be executed in the callback function
});

回调函数的优点

使用回调函数可以带来许多好处,包括:

  • 提高代码的可读性和可维护性
  • 提高代码的可重用性
  • 提高代码的灵活性
  • 提高代码的性能