Are callbacks in JavaScript just blank functions?
Callbacks are not just blank functions. They are functions that can be called (often with some arguments) sometime later. Sometimes, they are optional and a host function will let you pass the callback or not pass the callback. If the callback is not passed, the host function can detect that it was not passed as an argument and adapt its behavior accordingly.
What does the following statement mean?
callback = callback || function () {};
Does that mean callbacks are simply blank functions?
This is a common design pattern to ensure that an argument to a function has a meaningful value in case it was not passed by the caller so the function can proceed internally and execute normally assuming that argument was passed by the caller, even if the caller didn't pass the argument.
The code callback = callback || function () {};
is equivalent to this:
if (callback) {
callback = callback;
} else {
callback = function() {};
}
In Javascript, the ||
operator assigns the result to be the first of the two operands that is truthy (or false
if neither is truthy), so if callback
has a value, then it becomes the result of the ||
operand and you get callback = callback
. Otherwise if callback
is not truthy, it assigns callback
to have a default function value that allows the rest of the function to operate assuming that callback
has a legitimate value. This keeps all the rest of the function code from having to check if callback
has a legitimate value before using it.
Also, what's the difference between callback.call(this)
and
callback(anything)
?
someFunction.call()
allows you to the value of this
when the function runs. So callback.call(this)
makes the callback have the same value of this
when it runs that the current function does. If you just did callback(...)
without the .call()
, then this
will take on the default value which be either the window
object or, if running in strict mode, it will be undefined
.
If the particular callback doesn't happen to refer to the value of this
in its code, then there will be no difference in outcome by using .call()
or not using it, but in this case, it is an extra feature offered to the callback that it can access the current instance of the Store
object in use by accessing the this
value inside the callback.
Setting the value of this
like this allows you to use a method of the object as the direct callback since that is the same calling convention that an object method has.
So, if you had a Store
object like this:
var s = new Store();
And, there was a method of that object called setName()
that uses this
to refer to its own object instance, you could do:
s.findAll(s.setName);
This would only work because callback.call(this)
was setting the instance value into the value of this
in the callback.