Three minutes to learn JS callback function (callback)

Three minutes to learn JS callback function (callback)

What is a callback function?

  • When the program is running, under normal circumstances, the application will often call the pre-prepared functions in the library through the API.
  • But some library functions require the application to pass a function to it first, so that it can be called at the right time to complete the target task. The function that is passed in and then called is called the callback function

The above may not be well understood, let's give a chestnut:

你到一个商店买东西,刚好你要的东西没有货,于是你在店员那里留下了你的电话,
过了几天店里有货了,店员就打了你的电话,然后你接到电话后就到店里去取了货。
在这个例子里,你的电话号码就叫回调函数,你把电话留给店员就叫登记回调函数,
店里后来有货了叫做触发了回调关联的事件,店员给你打电话叫做调用回调函数,你到店里去取货叫做响应回调事件。

Now understand what a callback function is!

If you still don't understand, let's learn through examples!

Before learning the callback function, let's take a look at the following two pieces of code:
Let's guess the result of the code.

<script>
    function say(value) {
    
    
        alert(value);
    }
    alert(say);
    say(123);
</script>

If you test it, you will find:

只写变量名 say  返回的将会是 say方法本身,以字符串的形式表现出来。
而在变量名后加()如say()返回的就会使say方法调用后的结果,这里是弹出value的值。

Let's take a look at the following two pieces of code:

function say (value) {
    
    
    alert(value);
}
function execute (someFunction, value) {
    
    
    someFunction(value);
}
execute(say, 123);
function execute (someFunction, value) {
    
    
    someFunction(value);
}
execute(function(value){
    
    alert(value);}, 123);
  • The first piece of code above is to pass the say method as a parameter to the execute method
  • The second piece of code is to directly pass the anonymous function as a parameter to the execute method

The say or anonymous function here is called a callback function.

The callback function is easy to be confused-passing parameters

If the callback function needs to pass parameters, how to do it, here are two solutions.

  • Pass the parameters of the callback function as the parameters of the same level as the callback function

Insert picture description here

  • The parameters of the callback function are created inside the calling callback function

Insert picture description here
Callback function application scenarios are mostly used when writing components using JS, especially when many component events require the support of callback functions.

Insert picture description here

Guess you like

Origin blog.csdn.net/XVJINHUA954/article/details/111941313