Javascript Memoization Explanation?

前端 未结 6 1313
花落未央
花落未央 2020-12-11 02:51

Reading an example from a book, can someone explain how the function call to fibonacci takes in the argument \'i\' when the function itself doesn\'t declare any parameters?<

6条回答
  •  攒了一身酷
    2020-12-11 03:50

    You are creating a self-executing anonymous function (function(){}()); which inside it returns the fib function, which takes an argument. var fib = function(n){} ... return fib;

    var fibonacci = (function () { // Self-executing anonymous function
        var memo = [0, 1];         // local variable within anonymous function
        var fib = function (n) {   // actual fib function (takes one argument)
            var result = memo[n];
            if (typeof result !== 'number') {
                result = fib(n - 1) + fib(n - 2);
                memo[n] = result;
            }
            return result;
        };
        return fib; // return fib (fibonacci is now set to the function fib defined above, which takes one argument)
    }());
    

    This system (returning a function from a self-executing anonymous function) allows for you to define variable in a local scope that can still be used by the returned function, but not by functions outside the scope. Here is an example.

    This technique is called closure in JavaScript. Read more about it on the MDN guide.

提交回复
热议问题