javascript - Syntax of Closures -
function makeincreasebyfunction(increasebyamount) { return function (numbertoincrease) { return numbertoincrease + increasebyamount; }; } makeincreasebyfunction(3)(10); updated clarity can explain why (3)(10) written way is? understand 10 being supplied argument inner function, why syntactically notated this? if had 3 nested functions, arguments written in order in (3)(10)(20)?
with intermediate variable:
var increaseby3 = makeincreasebyfunction(3); var foo = increaseby3(10); without intermediate variable:
var foo = makeincreasebyfunction(3)(10); in both cases, first invokation passes argument 3 makeincreasebyfunction, , result returns inner function has closed on increasebyamount value of 3. whether create variable intermediate function returned makeincreasebyfunction, or invoke directly, same thing.
can explain little bit more detail how in var foo = makeincreasebyfunction(3)(10); 10 getting inner function? looks syntactically different how arguments passed in javascript me. – ggg
makeincreasebyfunction(3) returns function, "inner function" defined inside makeincreasebyfunction. functions, call function ( arguments ) syntax. can write if makes more sense way:
( makeincreasebyfunction(3) )(10) what happens here makeincreasebyfunction(3) gets called first , returns ⟪inner function⟫, , call ⟪inner function⟫(10).
if evaluating hand (i think meant "syntactically"), think of happening step-by-step this:
// original invocation var foo = makeincreasebyfunction(3)(10); // substitute definition of makeincreasebyfunction var foo = (function (increasebyamount) { return function (numbertoincrease) { return numbertoincrease + increasebyamount; }; })(3)(10); // apply parameter 3 var foo = (function (numbertoincrease) { return numbertoincrease + 3; })(10); // apply parameter 10 var foo = 10 + 3; // final result var foo = 13; note: if want technical, we're doing here 2 beta reductions—but unless have background lambda calculus confuse more you!
Comments
Post a Comment