A wonderful use of Javascript callback Functions
Preface
In fact, a callback function is a simple and popular function. 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 how to use the Javascript callback function.
Instance
A long time ago, there was a person.
var person;
He is an individual, that is, an object.
Person = {}; // in JavaScript, curly brackets represent an object.
He has a name named James.
Person. name = 'xiaoming ';
Let's see if it's really James.
alert(person.name);
Well, one day, James got 10 yuan.
Person. money = '10 money ';
If he had the money, he would spend 10 yuan.
James has a way to spend money.spendMoney ()
Person. spendMoney = function () {alert (this. name + "use" + this. money + "I bought a comic book for a dollar! ");}
Run:
person.spendMoney();
Prompt: James bought a comic book for 10 yuan.
Well, the question is, do James have to buy a comic book after spending money.
The fact is, what should we do with the money? It is up to him to decide. Because the money is in James's pocket.
Therefore, you can use the callback function.
The callback function itself is a data type.
In javaScript, the status of functions andString
,int
,boolean
And so on. They can all be considered as a data type.
Since it is a data type, it can be passed as a parameter.
So it should be like this:
person.spendMoney =function(doSomeThing){ doSomeThing(); }
Parentheses are used to execute the function.
A function without parentheses isString
,int
The same thing.
Is a data type.
Same.
This is written in JAVA:
String str ="HelloWorld!";
In JavaScript, functions are the same.
var say =function(){ alert('HelloWorld');}
At this timesay
Is a data type.
Because there are no parentheses, they will be executed only when they are in parentheses!
James made his decisions on what he made with ten yuan.
person.spendMoney(function(){});
In this way, the function is passed in.
Pass the FunctionspendMoney
The purpose of the method is to let the function be executed in it.
Therefore:
person.spendMoney =function(doSomeThing){ doSomeThing(); }
It is enclosed in parentheses to execute this function.
Decide what to do.
Person. spendMoney (function () {alert ('save the money! ');});
Summary
That is, you can pass a function as a parameter into a method and 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 for your learning and work. If you have any questions, leave a message for discussion.