javascript - 为什么在 JavaScript 中使用回调,它有什么优点?

标签 javascript jquery

有人可以解释一下,为什么我们在 JavaScript 中使用回调吗?我找到了例子,但它们可以通过使用普通函数来实现。使用它有什么好处?我得到了“如何”使用它的答案,而不是“为什么以及何时”我们需要使用它。

通常,我发现它在 AJAX 中使用。在 httpRequest.onreadystatechange 上。这和Java的多线程类似吗?听者如何以及在哪里回应? 异步编程类似于多线程吗?

在下面的代码中,控制流程是怎样的:

function some_function(arg1, arg2, callback) {
  var my_number = Math.ceil(Math.random() * (arg1 - arg2) + arg2);
  callback(my_number);
  some_different_function_not_callback(arg1);
}
some_function(5, 15, function(num) {
   console.log("callback called! " + num);
});

来自 JQuery 网站:

The special thing about a callback is that functions that appear after the "parent" can execute before the callback executes" (ref: http://docs.jquery.com/Tutorials:How_jQuery_Works)

有人可以用例子解释一下这句话吗?

最佳答案

主浏览器进程是单线程事件循环。如果您在单线程事件循环中执行长时间运行的操作,则进程会“阻塞”。这很糟糕,因为进程在等待操作完成时停止处理其他事件。 “alert”是少数阻止浏览器的方法之一:如果您调用alert('test'),您将无法再单击链接、执行ajax 查询或与浏览器UI 交互。

为了防止长时间运行的操作发生阻塞,XMLHttpRequest 提供了一个异步接口(interface)。您向其传递一个回调以在操作完成后运行,并且在处理时将控制权交还给主事件循环而不是阻塞。

没有理由使用回调,除非您想将某些内容绑定(bind)到事件处理程序,或者您的操作可能会阻塞,因此需要异步编程接口(interface)。

This is an excellent video discussing more about the event loop used in the browser, as well as on the server side in node.js.

编辑:jQuery 文档中的那条令人费解的行只是意味着回调异步执行,因为控制权被交还给主事件循环。

parent_function(function () { console.log('Callback'); });
parent_doesnt_block(); // <-- function appears after "parent"
therefore_execution_continues();
// Maybe we get 'Callback' in the console here? or maybe later...
execution_still_continues();

关于javascript - 为什么在 JavaScript 中使用回调,它有什么优点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7070495/

相关文章:

JavaScript:时钟和 Date()

javascript - 在 Chrome 上执行多个选择器时 jQuery 中的 INVALID_NODE_TYPE_ERR

javascript - 为什么我不能在 Internet Explorer 中使用 JavaScript 向 HTML 表格动态添加行?

javascript - 以一定速度滚动时,Masonry 和 Infinite Scroll 会破坏布局

jquery - 如何获取元素的第n个子元素

javascript - 有没有办法使用 cycle2 根据图像是垂直还是水平调整图像大小?

javascript - 如何将这些函数合并为具有属性的单个函数?

php - JQuery 发布和获取

javascript - 使用 jQuery 显示和隐藏动态生成的表格元素

javascript - 在另一个脚本之前等待脚本完全加载的正确方法是什么