Passing "extra" arguments to a function stored in a variable - Javascript -
i'm new javascript, i'm self-teaching, might obvious area, no matter how phrase question can't seem head around 1 issue. @ moment i'm reading through http://eloquentjavascript.net/chapter6.html (which on mozilla's mdn). i've come across couple of times now, simple break down if possible.
function negate(func) { return function(x) { return !func(x); }; } var isnotnan = negate(isnan); show(isnotnan(nan));
i don't understand how @ last step isnotnan (a variable) passing 'extra argument' (nan) function stored in isnotnan (negate(isnan). "show(isnotnan(nan));"
i came across same problem when concept of enclosure trying explained. don't argument "nan" going in above function, seems me last statement ends like:
show(negate(isnan, nan));
i happy provide more details. concept of passing argument variable holding function argument confuses hell out of me!
there's no "extra" argument. negate()
function returns function defined function expression, can called number of original (not extra) arguments passed. closure used returned function keep reference isnan
func
.
var isnotnan = negate(isnan);
at point, isnotnan
contains reference function
function(x) { return !func(x); };
again, func
here refers isnan
argument passed negate
function, immediate parent in scope chain. result similar, not same as
var isnotnan = function (x) { return !isnan(x); };
the reason not same is, if change value of isnan
, behaviour of function change. in example posted, however, value of func
equal original value of isnan
, cannot changed outside of scope closure.
essentially, can pass in function , new function returns negated result of original function in return. example:
var isnotarray = negate(array.isarray); isnotarray(12); //-> true
Comments
Post a Comment