How to explain callbacks in plain english? How are they different from calling one function from another function?

后端 未结 30 2159
时光说笑
时光说笑 2020-11-22 11: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 thei

30条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 11:19

    Imagine a friend is leaving your house, and you tell her "Call me when you get home so that I know you arrived safely"; that is (literally) a call back. That's what a callback function is, regardless of language. You want some procedure to pass control back to you when it has completed some task, so you give it a function to use to call back to you.

    In Python, for example,

    grabDBValue( (lambda x: passValueToGUIWindow(x) ))
    

    grabDBValue could be written to only grab a value from a database and then let you specify what to actually do with the value, so it accepts a function. You don't know when or if grabDBValue will return, but if/when it does, you know what you want it to do. Here, I pass in an anonymous function (or lambda) that sends the value to a GUI window. I could easily change the behavior of the program by doing this:

    grabDBValue( (lambda x: passToLogger(x) ))
    

    Callbacks work well in languages where functions are first class values, just like the usual integers, character strings, booleans, etc. In C, you can "pass" a function around by passing around a pointer to it and the caller can use that; in Java, the caller will ask for a static class of a certain type with a certain method name since there are no functions ("methods," really) outside of classes; and in most other dynamic languages you can just pass a function with simple syntax.

    Protip:

    In languages with lexical scoping (like Scheme or Perl) you can pull a trick like this:

    my $var = 2;
    my $val = someCallerBackFunction(sub callback { return $var * 3; });
    # Perlistas note: I know the sub doesn't need a name, this is for illustration
    

    $val in this case will be 6 because the callback has access to the variables declared in the lexical environment where it was defined. Lexical scope and anonymous callbacks are a powerful combination warranting further study for the novice programmer.

提交回复
热议问题