Call Back Function

In JavaScript, functions are first-class objects; that is, functions are of the type ob Object and they can be used in first-class manner like any other object (String, Array, Number, etc). They can be "stored in variables, passed as arguments to functions, created within functions, and returned from functions".

A callback function, also known as a higher-order function, is a function that is passed to another function (let’s call this other function “otherFunction”) as a parameter, and the callback function is called (or executed) inside the other Function.

A callback function is essentially a pattern (an established solution to a common problem), and therefore, the use of a callback function is also known as a callback pattern.

We can pass functions around like variables and return them in functions and use them in other functions. When we pass a callback function as an argument to another function, we are only passing the function definition. We are not executing the function in the parameter. In other words, we aren’t passing the function with the trailing pair of executing parenthesis () like we do when we are executing a function.

Callback functions are Closures

When we pass a callback function as an argument to another function, the callback is executed at some point inside the containing function’s body just as if the callback were defined in the containing function. This means the callback is a closure. As we know, closures have access to the containing function’s scope, so the callback function can access the containing functions’ variables, and even the variables from the global scope.

Use Named OR Anonymous Functions as Callbacks


// pass anonymous function 
$("#btn_1").click(function() {
      alert("Btn 1 Clicked");
});

// global variable​
var allUserData = [];
    ​
// generic logStuff function that prints to console​function logStuff (userData) {
    if ( typeof userData === "string")
     {
      console.log(userData);
     }
     else if ( typeof userData === "object")
     {
    for (var item in userData) {
       console.log(item + ": " + userData[item]);
     }
      }
}
    ​
// A function that takes two parameters, the last one a callback function​
function getInput (options, callback) {
     allUserData.push (options);
        callback (options);
}
    ​
// When we call the getInput function, we pass logStuff as a parameter.​// So logStuff will be the function that will called back (or executed) inside the getInput function​
 getInput ({name:"Rich", speciality:"JavaScript"}, logStuff);

​//  name: Rich​// speciality: JavaScript

Pass Parameters to Callback Functions

Since the callback function is just a normal function when it is executed, we can pass parameters to it. We can pass any of the containing function’s properties (or global properties) as parameters to the callback function.

//Global variable​var generalLastName = "Clinton";

function getInput (options, callback) {
      allUserData.push (options);
​// Pass the global variable generalLastName to the callback function​
       callback (generalLastName, options);
}

Make Sure Callback is a Function Before Executing It

function getInput(options, callback) {
     allUserData.push(options); 
     // Make sure the callback is a function​
     if (typeof callback === "function") {
      // Call it, since we have confirmed it is callable​
     callback(options);
      }
}

Problem When Using Methods With The this Object as Callbacks

When the callback function is a method that uses the this object, we have to modify how we execute the callback function to preserve the this object context. Or else the this object will either point to the global window object (in the browser), if callback was passed to a global function. Or it will point to the object of the containing method.

// Define an object with some properties and a method​// We will later pass the method as a callback function to another function​var clientData = {
        id: 094545,
        fullName: "Not Set",
        // setUserName is a method on the clientData object​
        setUserName: function (firstName, lastName)  {
            // this refers to the fullName property in this object​
          this.fullName = firstName + " " + lastName;
        }
}
    ​
​function getUserInput(firstName, lastName, callback)  {
        // Do other stuff to validate firstName/lastName here​// Now save the names​
        callback (firstName, lastName);
}

getUserInput ("Barack", "Obama", clientData.setUserName);
    ​
console.log (clientData.fullName);// Not Set​// The fullName property was initialized on the window object​
console.log (window.fullName); // Barack Obama

Use the Call or Apply Function To Preserve this

We can fix the preceding problem by using the Call or Apply function. And these methods are used to set the this object inside the function and to pass arguments to the functions.

Call takes the value to be used as the this object inside the function as the first parameter, and the remaining arguments to be passed to the function are passed individually (separated by commas of course). The Apply function’s first parameter is also the value to be used as the this object inside the function, while the last parameter is an array of values (or the arguments object) to pass to the function.

//Note that we have added an extra parameter for the callback object, called "callbackObj"​function getUserInput(firstName, lastName, callback, callbackObj)  {
   // Do other stuff to validate name here​// The use of the Apply function below will set the this object to be callbackObj​
  callback.apply (callbackObj, [firstName, lastName]);
}
    ​

results matching ""

    No results matching ""