Javscript closure questions
Posted
by Shuchun Yang
on Stack Overflow
See other posts from Stack Overflow
or by Shuchun Yang
Published on 2010-04-18T02:43:00Z
Indexed on
2010/04/18
2:53 UTC
Read the original article
Hit count: 507
JavaScript
|closure
While I was reading the book Javascript: The Good Parts. I can not understand the piece of code bellow:
We can generalize this by making a function that helps us make memoized functions. The memoizer function will take an initial memo array and the fundamental function. It returns a shell function that manages the memo store and that calls the fundamental function as needed. We pass the shell function and the function's parameters to the fundamental function:
var memoizer = function (memo, fundamental) { var shell = function (n) { var result = memo[n]; if (typeof result !== 'number') { result = fundamental(shell, n); memo[n] = result; } return result; }; return shell; };
We can now define fibonacci with the memoizer, providing the initial memo array and fundamental function:
var fibonacci = memoizer([0, 1], function (test, n) { return test(n - 1) + test(n - 2); });
My question is what is the test function? When does it get defined and invoked? It seems very confusing to me. Also I think this statement: memo[n] = result;
is useless. Please correct if I am wrong.
© Stack Overflow or respective owner