Functions are really objects: they can be “stored” in variables, passed as function arguments, created in functions, and returned from functions.
The callback function
One function is passed as an argument to another function (here we call the otherFunction “otherFunction”), and the callback function is called in otherFunction.
// The click method is a function, not a variable."#btn_1").click(function() {
alert("Btn 1 Clicked"); }); / / orfunction click() {// It is the callback function alert("Btn 1 Clicked");
}
$("#btn_1").click(click);
Copy the code
How does the callback function work
Because functions are first class objects in Javascript, we treat them like objects, so we can pass functions like variables, return functions within functions, and use functions in other functions. When we pass a callback function as an argument to another function, we simply pass the function definition. We are not executing functions in arguments. We do not pass functions with a pair of execution parentheses () as we normally execute functions.
It is important to note that the callback is not executed immediately. It will be “called back” (as its name suggests) at a specific point in time within the containing function
The rationale for implementing callback functions
Use named or anonymous functions as callbacks
As in the previous example, the first method is to use anonymous functions as callbacks (using anonymous functions defined by parameter positions as callbacks). The second way is to name the function as a callback (define a named function and pass the function name as a variable to the function)
Pass arguments to the callback function
Var generalLastName ="Cliton";
functiongetInput(options, callback){ var arr = []; arr.push(options); // Pass the global variable generalLastName to callback(generalLastName,arr); } getInput({name:"Rich",speciality:"Javascript"}, function(generalLastName,arr){
console.log(generalLastName + ":"+ arr[0].speciality) // Cliton:Javascript }); // The second way is to name the function as the callback var generalLastName ="Cliton";
functiongetInput(options, callback){ var arr = []; arr.push(options); // Pass the global variable generalLastName to callback(generalLastName,arr); }function call(generalLastName,arr){
console.log(generalLastName + ":" + arr[0].speciality) // Cliton:Javascript
}
getInput({name:"Rich",speciality:"Javascript"}, call);
Copy the code
Ensure that the callback function is a function before execution
functionGetInput (options, callback){// Make sure callback is a functionif(typeof callback === "function"){// Call it, now that we've determined that it's callable callback(options); }}Copy the code
Call back to Hell (call back to 18 layers of Hell)
var p_client = new Db('integration_tests_20', new Server("127.0.0.1", 27017, {}), {'pk':CustomPKFactory});
p_client.open(function(err, p_client) {
p_client.dropDatabase(function(err, done) {
p_client.createCollection('test_custom_key'.function(err, collection) {
collection.insert({'a': 1}.function(err, docs) {
collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}, function(err, cursor) {
cursor.toArray(function(err, items) {
test.assertEquals(1, items.length);
// Let's close the db p_client.close(); }); }); }); }); }); }); Solution: 1. Name your functions and pass their names as callbacks, instead of defining anonymous functions as arguments to the main function. Modularity L separates your code into modules, so that you can place pieces of code around to do specific work. You can then import modules into your giant application.Copy the code
Create your own callback function
// Callback, the last parameter, will be the genericPoemMaker function we defined abovefunction getUserInput(firstName, lastName, gender, callback) {
var fullName = firstName + "" + lastName;
if (typeof callback === "function") { callback(fullName, gender); }}function genericPoemMaker(name, gender) {
console.log(name + " is finer than fine wine.");
console.log("Altruistic and noble for the modern time.");
console.log("Always admirably adorned with the latest style.");
console.log("A " + gender + " of unfortunate tragedies who still manages a perpetual smile");
}
getUserInput("Michael"."Fassbender"."Man", genericPoemMaker); // The first method: name the function as the callback function getUserInput("Michael"."Fassbender"."Man".function(name, gender){// Second method: anonymous function as callback function console.log(name +" is finer than fine wine.");
console.log("Altruistic and noble for the modern time.");
console.log("Always admirably adorned with the latest style.");
console.log("A " + gender + " of unfortunate tragedies who still manages a perpetual smile");
});
Copy the code