Home  >  Article  >  Web Front-end  >  Detailed explanation of JS callback function examples

Detailed explanation of JS callback function examples

php中世界最好的语言
php中世界最好的语言Original
2018-05-03 16:18:451552browse

This time I will bring you a detailed explanation of JScallback function examples and precautions when using JS callback functions. The following is a practical case, let’s take a look.

Before talking about the callback function, you might as well look at a piece of code first. I believe that students with some basic knowledge of js can understand its meaning:

document.getElementById('demo').click=function(){
  alert(1);
};

This code is actually an event callback. Write it like this In fact, it is relatively vague. Let’s take a look at the following code.

document.getElementById('demo').addEventListener('click',function(){
    alert(1)
});

The two pieces of code actually do the same thing. The only difference is the way of writing. Let’s look at thisaddEventListener('eventName ',callback),addEventListenerThis function has two parameters, the first is the event name, and the second parameter is actually the callback function. According to the callback function in the book, the function Since the parameter in can be a variable, it can also be a function. Maybe everyone is still confused about returning functions at this point. Let's look at the next example.

function demo(a,b,callback){
    let c=a+b;
    callback(c);
};
demo(1,2,function(c){
    alert(c);//3
})

This code defines a demo function. This function has three parameters a, b, callback. We declare a local variable c inside this function, and then execute our callback (callback function), then Come down and execute the demo function

The three parameters of this function are as above, and the value 3 pops up in the callback function. This is a simple callback function. To truly understand the meaning of the callback function, I actually think it depends on understanding its purpose. Only by understanding its purpose can we truly understand it.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the use of computed in Vue.js

js verification of birth date regular expression

The above is the detailed content of Detailed explanation of JS callback function examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn