JavaScript回调函数– JS中的回调是什么以及如何使用它们

If you’re familiar with programming, you already know what functions do and how to use them. But what is a callback function? Callback functions are an important part of JavaScript and once you understand how callbacks work, you’ll become much better in JavaScript.

如果您熟悉编程,那么您已经知道什么功能可以使用以及如何使用它们。 但是什么是回调函数? 回调函数是JavaScript的重要组成部分,一旦您了解了回调的工作原理,JavaScript就会变得更好。

So in this post, I would like to help you to understand what callback functions are and how to use them in JavaScript by going through some examples.

因此,在本文中,我将通过一些示例来帮助您了解什么是回调函数以及如何在JavaScript中使用它们。

什么是回调函数? (What is a Callback Function?)

In JavaScript, functions are objects. Can we pass objects to functions as parameters? Yes.

在JavaScript中,函数是对象。 我们可以将对象作为参数传递给函数吗? 是。

So, we can also pass functions as parameters to other functions and call them inside the outer functions. Sounds complicated? Let me show that in an example below:

因此,我们还可以将函数作为参数传递给其他函数,并在外部函数中调用它们。 听起来复杂吗? 让我在下面的示例中展示一下:

function print(callback) {  
    callback();
}

The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function. But that’s not all.

print()函数将另一个函数作为参数并在内部调用它。 这在JavaScript中有效,我们称之为“回调”。 因此,作为参数传递给另一个函数的函数是回调函数。 但这还不是全部。

You can also watch the video version of callback functions below:

您还可以在下面观看回调函数的视频版本:

为什么需要回调函数? (Why do we need Callback Functions?)

JavaScript runs code sequentially in top-down order. However, there are some cases that code runs (or must run) after something else happens and also not sequentially. This is called asynchronous programming.

JavaScript按自上而下的顺序顺序运行代码。 但是,在某些情况下,代码会在发生其他事情之后运行(或必须运行),并且也不会顺序运行。 这称为异步编程。

Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors.

回调确保函数在任务完成之前不会运行,而是在任务完成之后立即运行。 它可以帮助我们开发异步JavaScript代码,并确保我们免受问题和错误的侵害。

In JavaScript, the way to create a callback function is to pass it as a parameter to another function, and then to call it back right after something has happened or some task is completed. Let’s see how…

在JavaScript中,创建回调函数的方法是将其作为参数传递给另一个函数,然后在发生某些情况或完成某些任务后立即对其进行回调。 让我们看看如何...

如何建立回呼 (How to create a Callback)

To understand what I’ve explained above, let me start with a simple example. We want to log a message to the console but it should be there after 3 seconds.

为了理解我上面解释的内容,让我从一个简单的示例开始。 我们想将一条消息记录到控制台,但是它应该在3秒钟后存在。

const message = function() {  
    console.log("This message is shown after 3 seconds");
}
 
setTimeout(message, 3000);

There is a built-in method in JavaScript called “setTimeout”, which calls a function or evaluates an expression after a given period of time (in milliseconds). So here, the “message” function is being called after 3 seconds have passed. (1 second = 1000 milliseconds)

JavaScript中有一个称为“ setTimeout”的内置方法,该方法在给定的时间段(以毫秒为单位)后调用函数或评估表达式。 因此,在这里,经过3秒后将调用“消息”功能。 (1秒= 1000毫秒)

In other words, the message function is being called after something happened (after 3 seconds passed for this example), but not before. So the message function is an example of a callback function.

换句话说,消息函数是在发生某件事之后(在本例中为3秒之后)而不是之前被调用的。 因此,消息函数是回调函数的示例。

什么是匿名函数? (What is an Anonymous Function?)

Alternatively, we can define a function directly inside another function, instead of calling it. It will look like this:

另外,我们可以在另一个函数内部直接定义一个函数,而不是调用它。 它看起来像这样:

setTimeout(function() {  
    console.log("This message is shown after 3 seconds");
}, 3000);

As we can see, the callback function here has no name and a function definition without a name in JavaScript is called as an “anonymous function”. This does exactly the same task as the example above.

如我们所见,这里的回调函数没有名称,JavaScript中没有名称的函数定义被称为“匿名函数”。 这与上面的示例完全相同。

回调作为箭头函数 (Callback as an Arrow Function)

If you prefer, you can also write the same callback function as an ES6 arrow function, which is a newer type of function in JavaScript:

如果愿意,还可以编写与ES6箭头函数相同的回调函数,这是JavaScript中较新的函数类型:

setTimeout(() => { 
    console.log("This message is shown after 3 seconds");
}, 3000);

那事件呢? (What about Events?)

JavaScript is an event-driven programming language. We also use callback functions for event declarations. For example, let’s say we want users to click on a button:

JavaScript是一种事件驱动的编程语言。 我们还将回调函数用于事件声明。 例如,假设我们希望用户单击按钮:

<button id="callback-btn">Click here</button>

This time we will see a message on the console only when the user clicks on the button:

这次,只有当用户单击按钮时,我们才会在控制台上看到一条消息:

document.queryselector("#callback-btn")
    .addEventListener("click", function() {    
      console.log("User has clicked on the button!");
});

So here we select the button first with its id, and then we add an event listener with the addEventListener method. It takes 2 parameters. The first one is its type, “click”, and the second parameter is a callback function, which logs the message when the button is clicked.

因此,在这里我们首先选择具有其ID的按钮,然后使用addEventListener方法添加一个事件侦听器。 它需要2个参数。 第一个是其类型,即“单击”,第二个参数是回调函数,该函数记录单击按钮时的消息。

As you can see, callback functions are also used for event declarations in JavaScript.

如您所见,回调函数也用于JavaScript中的事件声明。

结语 (Wrap up)

Callbacks are used often in JavaScript, and I hope this post helps you understand what they actually do and how to work with them easier. Next, you can learn about JavaScript Promises which is a similar topic that I've explained in my new post.

回调通常在JavaScript中使用,我希望本文能帮助您了解它们的实际作用以及如何更轻松地使用它们。 接下来,您可以了解JavaScript Promises ,这是我在新文章中介绍的类似主题。

If you want to learn more about web development, feel free to follow me on Youtube!

如果您想了解有关Web开发的更多信息,请随时 在YouTube上关注我

Thank you for reading!

感谢您的阅读!

翻译自: https://www.freecodecamp.org/news/javascript-callback-functions-what-are-callbacks-in-js-and-how-to-use-them/

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值