Does this fit your definition of a Callback?

2019-04-28 14:35发布

问题:

Definition of Callback:

A Function that is set as a property within a Component. And is usually called when some event occurs on the Component.

For Example:

If you wish to display a dialog which reads "I was clicked" when the user clicks on the Component componentB, you would write a method stored as a variable which does this:

var mouseDownCallbackFunction = function() {
    alert("I was clicked!");
};

Next, you would set this function inside the component like so...

// Set the Component to display the dialog when the 
// user presses the mouse down on it.
componentB.setMouseDownCallback(mouseDownCallbackFunction);

And this would cause mouseDownCallbackFunction to display "I was clicked" in an alert box when the component was clicked.

回答1:

In C, that would be a valid callback. However I'm not so familar with JavaScript to say if it is or not because I'm not sure how variables are treated with respect to their memory locations.

In C/C++ you could declare a void pointer:

void aFunction()
{
     do stuff
}

int main()
{
    void* myCallback = &aFunction; 
    componentB.setMouseDownCallback(myCallback);
}

Would work.

However, despite my lack of JavaScript knowledge, I do know that

componentB.setMouseDownCallback(function() {
        alert("I was clicked!");
        };
);

is valid as well.

EDIT added a not to the second sentence: "I'm not so familar"



回答2:

Yes, this is describing the exact definition of a callback...



回答3:

In JavaScript, technically, that's a closure, since it can bind to any variables in scope which are referenced.

But closures are just a better form of callback, so yes that's a callback. A callback in C is more primitive, providing only a pointer reference to a typed function, without binding to any context.



回答4:

Yes, a callback is a function that's defined at a higher level than it is called. Your client code creates the function, then passes it as a parameter to componentB, in order for componentB to call it later.



回答5:

yes, that's a callback.