简体   繁体   English

回调函数与从函数内部调用函数

[英]callback function vs calling a function from inside the function

I'm trying to understand JS and I'm really confused by the callback pattern. 我试图理解JS,并且对回调模式感到困惑。

function one(){
    alert("I'm one!")
}

function total(arg, callback){
    setTimeout(function() {alert("I'm "+arg);}, 1000);
    callback();
}

total('all', one);

versus

function one(){
    alert("I'm one!")
}

function total(arg){
    setTimeout(function() {alert("I'm "+arg);}, 1000);
    one();
}

total('all');

What is the benefit of passing one() as a parameter vs just calling it from within the function? one()作为参数传递而不是仅从函数内部调用它有什么好处?

If you know that you're always going to call one , there's no need to accept it as an input parameter; 如果您知道总是要调用one ,则无需接受它作为输入参数; you can just go ahead and call it. 您可以继续拨打电话。

The ability to accept callbacks allows you to easily write loosely coupled code. 接受回调的功能使您可以轻松编写松耦合的代码。

You are, for instance, passing a callback to setTimeout in your code example. 例如,您正在代码示例中将回调传递给setTimeout setTimeout knows to wait a given number of milliseconds before a function is called, but it doesn't know which function to call. setTimeout知道在调用函数之前要等待给定的毫秒数,但是它不知道要调用哪个函数。

Passing in callback functions allows you to dynamically affect the flow of the program. 传递回调函数使您可以动态影响程序的流程。 Additionally, you could pass the outcome of total as a parameter to callback , which is often used to enable asynchronous programming. 另外,您可以将total的结果作为参数传递给callback ,该参数通常用于启用异步编程。

function one(){
  alert("I'm one!")
}

function total(arg, callback){
  setTimeout(function() {
    if (callback) {
      callback();
    }
  }, 1000);
}

I suspect that your examples are not what was intended to showcase what a callback is. 我怀疑您的示例不是用来说明回调是什么。 Does this make more sense? 这更有意义吗?

function cb(arg){
    alert("I'm "+arg+"!")
}

function total(arg, callback){
    setTimeout(callback, 1000, arg);
}

total('one', cb);

Callback argument allows you to define custom interaction. 回调参数允许您定义自定义交互。 It's commonly used with any asynchronous operation to allow reacting of state change (for example when operation is done, or errored). 它通常与任何异步操作一起使用,以允许对状态更改做出反应(例如,当操作完成或出错时)。

One example of that may be an AJAX call (here with jQuery for simpliciy): 其中一个示例可能是AJAX调用(此处为简化起见,使用jQuery):

var request = $.ajax({
    url: "script.php"
});

// this allows you to specify custom action handling
request.done(one);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM