Preface
In fact, the simple point of the callback function is that when there are two functions a and b, when a is passed to b as a parameter and executed in b, a is a callback function. If a is an anonymous function, it is an anonymous callback function. Let's use an example to explain in detail how to use Javascript callback function.
Example
A long time ago, there was a man.
var person;
He is an individual, that is, an object.
person= {}; // In JavaScript, curly braces represent an objectHe has a name called Xiao Ming.
person.name = 'Xiao Ming';
Let's see if it's really called Xiao Ming.
alert(person.name);
Well, one day, Xiao Ming picked up 10 yuan.
person.money = '10 yuan';
He had to spend money, so he planned to spend 10 yuan.
Xiao Ming has a way spendMoney ()
person.spendMoney =function(){ alert(this.name +"used"+this.money +" I bought a comic book for RMB!"); }run:
person.spendMoney();
A pop-up reminder: Xiao Ming bought a comic book for 10 yuan.
Okay, the question is, does Xiao Ming have to buy comic books if he spends money? It must be no.
The fact should be that he has the final say on what to do with the money. Because the money is in Xiao Ming's pocket.
So, you can use the callback function.
The callback function itself is a data type.
In javaScript, the status of a function is the same as String , int , boolean , etc. in java, and can be regarded as a data type.
Since it is a data type, it can of course be passed as a parameter.
So it should be like this:
person.spendMoney =function(doSomeThing){ doSomeThing(); }Putting a bracket means executing the function.
Functions without brackets are the same thing as String and int .
is a data type.
Same.
This is what JAVA says:
String str ="HelloWorld!";
In JavaScript, functions are the same.
var says =function(){ alert('HelloWorld');} At this time, say is a data type.
Because there are no brackets, he will execute it only after brackets!
What Xiao Ming does with ten yuan, he has the final say.
person.spendMoney(function(){});This is to pass the function in.
The purpose of passing a function into spendMoney method is to let the function be executed in it.
so:
person.spendMoney =function(doSomeThing){ doSomeThing(); }There are brackets inside, which means that the function is to be executed.
What to do, decide for yourself.
person.spendMoney(function(){ alert('Let's save the money!'); });Summarize
It means that you can pass the function as a parameter into a method, and you can execute this function in the method. This is the magic of the callback function unique to js.
The above is all about the usage of Javascript callback functions. I hope it will be helpful to everyone's study and work. If you have any questions, please leave a message to discuss.