Seeing this block from jQuery.scrollTo.js
library (in v1.4 at line 184).
function animate( callback ){
$elem.animate( attr, duration, settings.easing, callback && function(){
callback.call(this, target, settings);
});
};
Curious to know how the comparison is going to work with
callback && function() {callback.call(...)};
and what's exactly the meaning behind this. Thanks in advance.
The callback && function() {callback.call(...)};
is doing two things:
callback
has been defined andJavaScript has a feature called "short-circuiting logical expressions". If a part of a logical expression cannot change the overall result, it is not going to be evaluated.
If callback
is undefined
, then it evaluates to false in the context of a logical expression (it's "falsy"). So the expression becomes the equivalent of false && ...
, in which case it does not matter anymore what ...
actually is, the result will always be false †1. JavaScript is not looking at the ...
in this case.
If callback
is not undefined
(but a function), the first part of the logical expression evaluates to true (it's "truthy"). At this point JavaScript evaluates the ...
. The overall result happens to be a function expression. The function expression results in an anonymous function, which is then passed to jQuery's animate()
.
The callback.call()
executes callback
and determines the meaning of this
within callback
. So callback.call(this)
makes sure that this
refers to the same object as in the outer function.
†1To be absolutely correct: The overall result of the expression will not be false
, it will be undefined
.
callback && function() {callback.call(...)};
This will check if the callback is truthy (is not false, 0, "", null, undefined, NaN) and if it is truthy and second part of the statement will be evaluated which will return function that will be passed in as a argument.
Example:
var test = true && function() {};
console.log(typeof test); // "function"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With