Callback Function

Callback Function

??A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

??In?computer programming, a?callback, also known as a "call-after" ?function, is any?executable code?that is passed as an?argument?to other code; that other code is expected to?call back?(execute) the argument at a given time.

??This execution may be immediate as in a?synchronous callback, or it might happen at a later point in time as in an?asynchronous callback.

??Programming languages?support callbacks in different ways, often implementing them with?subroutines,?lambda expressions,?blocks, or?function pointers.


Why callback function is used?

·????????Callbacks are?a great way to handle something after something else has been completed.

·????????By something here we mean a function execution. If we want to execute a function right after the return of some other function, then callbacks can be used.


When would you use a callback function?

??Callbacks make sure that?a function is not going to run before a task is completed but will run right after the task has completed.

??It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors.

The form of a callback varies among?programming languages:

  • In?assembly,?C,?C++,?Pascal,?Modula2?and similar languages, a machine-level?pointer?to a function may be passed as an argument to another (internal or external) function. This is supported by most compilers and provides the advantage of using different languages together without special wrapper libraries or classes. One example may be the?Windows API?that is directly (more or less) accessible by many different languages, compilers and assemblers.
  • C++ allows objects to provide their own implementation of the function call operation. The?Standard Template Library?accepts these objects (called?functors), as well as function pointers, as parameters to various polymorphic algorithms.
  • Many?dynamic languages, such as?JavaScript,?Lua,?Python,?Perl[2][3]?and?PHP, simply allow a function object to be passed through.
  • CLI languages?such as?C#?and?VB.NET?provide a?type-safe?encapsulating reference, a "delegate", to define well-typed?function pointers. These can be used as callbacks.
  • Events and?event handlers, as used in .NET languages, provide generalized syntax for callbacks.
  • Functional languages generally support?first-class functions, which can be passed as callbacks to other functions, stored as data or returned from functions.
  • Some languages, such as?Algol 68, Perl, Python,?Ruby,?Smalltalk,?C++11?and later, newer versions of C# and VB.NET as well as most functional languages, allow unnamed blocks of code (lambda expressions) to be supplied instead of references to functions defined elsewhere.
  • In some languages, e.g.?Scheme,?ML, JavaScript, Perl, Python, Smalltalk, PHP (since 5.3.0),[4]?C++11 and later, Java (since 8),[5]?and many others, such functions can be?closures, i.e. they can access and modify variables locally defined in the context in which the function was defined. Note that Java cannot, however, modify the local variables in the enclosing scope.
  • In?object-oriented programming?languages without function-valued arguments, such as in?Java?before its 8 version, callbacks can be simulated by passing an instance of an abstract class or interface, of which the receiver will call one or more methods, while the calling end provides a concrete implementation. Such objects are effectively a bundle of callbacks, plus the data they need to manipulate[clarification needed]. They are useful in implementing various?design patterns?such as?Visitor,?Observer, and?Strategy.


Example:

1.??????JavaScript :

·????????Callbacks are used in the implementation of languages such as?JavaScript, including support of JavaScript functions as callbacks through Js-c types and in components such as addEventListener.


function calculate(num1, num2, callbackFunction) {

return callbackFunction(num1, num2);

}

function calcProduct(num1, num2) {

return num1 * num2;

}

function calcSum(num1, num2) {

return num1 + num2;

}

// alerts 75, the product of 5 and 15

alert(calculate(5, 15, calcProduct));

// alerts 20, the sum of 5 and 15

alert(calculate(5, 15, calcSum));


2.??????C :

·????????Callbacks have a wide variety of uses, for example in error signaling: a?Unix?program might not want to terminate immediately when it receives?SIGTERM, so to make sure that its termination is handled properly, it would register the cleanup function as a callback.

·????????Callbacks may also be used to control whether a function acts or not:?Xlibrary?allows custom predicates to be specified to determine whether a program wishes to handle an event.

?

#include <stdio.h>

#include <stdlib.h>

/* The calling function takes a single callback as a parameter. */

void PrintTwoNumbers(int (*numberSource)(void)) {

???int val1 = numberSource();

???int val2 = numberSource();

???printf("%d and %d\n", val1, val2);

}

/* A possible callback */

int overNineThousand(void) {

???return (rand()%1000) + 9001;

}

/* Another possible callback. */

int meaningOfLife(void) {

???return 42;

  • }

/* Here we call PrintTwoNumbers() with three different callbacks. */

int main(void) {

???time_t t;

???srand((unsigned)time(&t)); // Init seed for random function

???PrintTwoNumbers(&rand);

???PrintTwoNumbers(&overNineThousand);

???PrintTwoNumbers(&meaningOfLife);

???return 0;

}

Example output:

20437 and 27669
9230 and 9014
42 and 42        

?

?



要查看或添加评论,请登录

社区洞察

其他会员也浏览了