How to explain callbacks in plain english? How are

2018-12-31 17:13发布

How to explain callbacks in plain English? How are they different from calling one function from another function taking some context from the calling function? How can their power be explained to a novice programmer?

30条回答
查无此人
2楼-- · 2018-12-31 17:24

Usually we sent variables to functions . Suppose you have task where the variable needs to be processed before being given as an argument - you can use callback .

function1(var1, var2) is the usual way .

What if I want var2 to be processed and then sent as an argument? function1(var1, function2(var2))

This is one type of callback - where function2 executes some code and returns a variable back to the initial function .

查看更多
只靠听说
3楼-- · 2018-12-31 17:26

Often an application needs to execute different functions based upon its context/state. For this, we use a variable where we would store the information about the function to be called. ‪According to its need the application will set this variable with the information about function to be called and will call the function using the same variable.

In javascript, the example is below. Here we use method argument as a variable where we store information about function.

function processArray(arr, callback) {
    var resultArr = new Array(); 
    for (var i = arr.length-1; i >= 0; i--)
        resultArr[i] = callback(arr[i]);
    return resultArr;
}

var arr = [1, 2, 3, 4];
var arrReturned = processArray(arr, function(arg) {return arg * -1;});
// arrReturned would be [-1, -2, -3, -4]
查看更多
皆成旧梦
4楼-- · 2018-12-31 17:26

Imagine you need a function that returns 10 squared so you write a function:

function tenSquared() {return 10*10;}

Later you need 9 squared so you write another function:

function nineSquared() {return 9*9;}

Eventually you will replace all of these with a generic function:

function square(x) {return x*x;}

The exact same thinking applies for callbacks. You have a function that does something and when done calls doA:

function computeA(){
    ...
    doA(result);
}

Later you want the exact same function to call doB instead you could duplicate the whole function:

function computeB(){
    ...
    doB(result);
}

Or you could pass a callback function as a variable and only have to have the function once:

function compute(callback){
    ...
    callback(result);
}

Then you just have to call compute(doA) and compute(doB).

Beyond simplifying code, it lets asynchronous code let you know it has completed by calling your arbitrary function on completion, similar to when you call someone on the phone and leave a callback number.

查看更多
泪湿衣
5楼-- · 2018-12-31 17:27

For teaching callbacks, you have to teach the pointer first. Once the students understand the idea of pointer to a variable, idea of callbacks will get easier. Assuming you are using C/C++, these steps can be followed.

  • First show your students how to use and manipulate variables using pointers alongside using the normal variable identifiers.
  • Then teach them there are things that can be done only with pointers(like passing a variable by reference).
  • Then tell them how executable code or functions are just like some other data(or variables) in the memory. So, functions also have addresses or pointers.
  • Then show them how functions can be called with function pointers and tell these are called callbacks.
  • Now, the question is, why all these hassle for calling some functions? What is the benefit? Like data pointers, function pointer aka callbacks has some advantages over using normal identifiers.
  • The first one is, function identifiers or function names cannot be used as normal data. I mean, you cannot make a data structure with functions(like an array or a linked list of functions). But with callbacks, you can make an array, a linked list or use them with other data like in dictionary of key-value pairs or trees, or any other things. This is a powerful benefit. And other benefits are actually child of this one.
  • The most common use of callbacks is seen in event driver programming. Where one or more functions are executed based on some incoming signal. With callbacks, a dictionary can be maintained to map signals with callbacks. Then the input signal resolution and execution of corresponding code become much easier.
  • The second use of callbacks coming in my mind is higher order functions. The functions which takes other functions as input arguments. And to send functions as arguments, we need callbacks. An example can be a function which take an array and a callback. Then it performs the callback on each of the item of the array and return the results in another array. If we pass the function a doubling callback, we get a doubled valued array. If we pass a squaring callback, we get squares. For square roots, just send appropriate callback. This cannot be done with normal functions.

There might many more things. Involve the students and they will discover. Hope this helps.

查看更多
琉璃瓶的回忆
6楼-- · 2018-12-31 17:28

I think it's an rather easy task to explain.

At first callback are just ordinary functions.
And the further is, that we call this function (let's call it A) from inside another function (let's call it B).

The magic about this is that I decide, which function should be called by the function from outside B.

At the time I write the function B I don't know which callback function should be called. At the time I call function B I also tell this function to call function A. That is all.

查看更多
呛了眼睛熬了心
7楼-- · 2018-12-31 17:29

Callbacks allows you to insert your own code into another block of code to be executed at another time, that modifies or adds to the behavior of that other block of code to suit your needs. You gain flexibility and customizability while being able to have more maintainable code.

Less hardcode = easier to maintain and change = less time = more business value = awesomeness.

For example, in javascript, using Underscore.js, you could find all even elements in an array like this:

var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]

Example courtesy of Underscore.js: http://documentcloud.github.com/underscore/#filter

查看更多
登录 后发表回答