In http://eloquentjavascript.net/1st_edition/chapter6.html, there is the following example:
function negate(func) {
return function(x) {
return !func(x);
};
}
var isNotNaN = negate(isNaN);
alert(isNotNaN(NaN));
Knowing only basic JavaScript and imperative programming, I am stumped by this programming style. What happens during runtime?
I stepped through the code and inspected variables and found that the value of x is NaN. How does it know that the argument to isNaN should be passed as argument x of the anonymous function? In the first place, why does the actual parameter NaN of isNotNaN become the argument to isNaN (ie while isNaN expects an argument, why does it take it from the argument of isNotNaN)?
NaNofisNotNaNbecome the argument toisNaN" Because of the third line:func(x).funcis a reference toisNaNandxisNaN. This is not much different from any other function E.g. infunction foo(x) { return bar(x); }; foo(x),foopassesxalong tobar. The only difference in your example is thatfuncis determined dynamically.negatecorrectly work only with functions that takes just one parameter