回调
一句话解释
回调是 函数通过 as 实参到 another 函数, 到是 called later 当事件 or 操作 completes.
用大白话说
A callback is a function you give to another function, saying "call 这个当你是做." The receiving function calls your callback at the appropriate time — after an operation completes, when data is ready, or when an event occurs.
Callbacks are everywhere in JavaScript: event handlers (call this function when the user clicks), array methods (call this function for each element), and asynchronous operations (call this function when the data arrives).
For example, arr.映射(回调) calls your callback once for each element. button.addEventListener('点击', 回调) calls your callback when the button is clicked. The pattern is the same: you provide a function, and something else calls it at the right time.
示例
// Callback with array method
const doubled = [1, 2, 3].map(n => n * 2);
console.log(doubled); // [2, 4, 6]
// Callback with event handler
button.addEventListener('click', function() {
console.log('Button was clicked!');
});
// Callback with asynchronous operation
setTimeout(() => {
console.log('This runs after 1 second');
}, 1000);In 每个情况, 函数是 通过 as 实参 and called later 通过接收函数 — 那个是 回调.
常见混淆
容易混淆的对象: Promise
关键区别: 回调是 函数通过到 是 called later; Promise 是对象 representing future 值. Promise 是创建到 handle 异步操作更多 cleanly than nested 回调 (回调 hell).
相关术语
相关资源
相关课程
- 函数
学习关于函数 and 回调.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。