Objective
In fact, the callback function is a simple popular point when there are A and B two functions, when a is passed as a parameter to B and executed in B, then A is a callback (callback) function, if a is an anonymous function, Then the anonymous callback function below is an example of how JavaScript callback functions are used.
Instance
A long time ago, there was a man.
He is an individual, or an object.
person= {}; In JavaScript, curly braces represent an object
He has a name called Xiaoming.
Person.name = ' xiaoming ';
See if it's really called xiaoming.
Well, one day, Xiaoming picked up 10 bucks.
Person.money = ' 10 dollars ';
With money to spend, he plans to use 10 dollars.
Xiaoming has a way of spending moneyspendMoney ()
Person.spendmoney =function () { alert (this.name +) bought a comic book with "+this.money +" block money! "); }
Run:
Pop-up tip: Xiaoming bought a comic book with 10 dollars.
Well, the problem is, Xiaoming has to buy comic books, certainly not.
The truth is, it's up to him to decide 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 is itself a data type.
In JavaScript, the status of functions is the same as in Java String
, and so on, and can be viewed as int
boolean
a data type.
Since it is a data type, it can certainly be passed as a parameter.
And so it should be:
Person.spendmoney =function (dosomething) { dosomething (); }
The parentheses are the meaning of the execution function.
The function with no parentheses is the String
int
same thing as the.
is a data type.
The same.
This is what Java will say:
String str = "helloworld!";
In JavaScript, functions are the same.
var say =function () {
alert (' HelloWorld ');
}
This say
is a data type.
Because there is no brace, he will not execute until the parentheses are made!
What xiaoming does with ten dollars, he decides for himself.
Person.spendmoney (function () {});
This is where the function is passed in.
The purpose of passing a function into a spendMoney
method is to allow the function to execute inside.
So:
Person.spendmoney =function (dosomething) { dosomething ();}
Inside, the parentheses are represented to perform this function.
What to do, decide for yourself.
Person.spendmoney (function () { alert (') Save the money! '); });
Summarize
That is, you can pass a function as a parameter into a method, and you can execute the function in the method, which is the magic of the JS-specific callback function.
The above is all about the usage of JavaScript callback functions, and I hope it will help you with your study and work. If you have questions, you can leave a message for discussion.