Javascript Memoization Explanation?

前端 未结 6 1332
花落未央
花落未央 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:52

    To understand this, I think it is helpful to work with a simpler example. Take a look at the two memoized functions below. The only difference is the () after add : function (){ ... }() on the successful memorization code.

        var failed_memoization = {
            add : function (){
                var counter;
                return function(number){
                    if(counter){
                        counter = counter + number;
                        return counter;
                    }
                    counter = number;
                    return counter;
                } //NOTE: NO function call brackets here
            }
        }
    
        var successful_memoization = {
            add : function (){
                var counter;
                return function(number){
                    if(counter){
                        counter = counter + number;
                        return counter;
                    }
                    counter = number;
                    return counter;
                }
            }()  //NOTE: the function call brackets here!!
        };
    }
    

    Now let's execute these two functions.

    console.log('Failed Memoization');
    console.log(failed_memoization.add(5));      //We wanted 5, but this prints the text of the function instead.... Okay, lets try something else
    console.log(failed_memoization.add()(5));    //5
    console.log(failed_memoization.add()(10));   //10 (Wanted it to be 5+10 = 15.
    console.log('successful_memoization');
    console.log(successful_memoization.add(8));  //8
    console.log(successful_memoization.add(16)); //24 (This is what we wanted 8 + 16 = 24)
    

    So what's going on here is that for successful_memoization when we put () to the end of its add : function(){...}(). As such, this function is executed immediately on the creation of the static object. In turn, executing that function returns the object function (number){...} wich results in the assignment: add : function (number){...} NOT add : function(){} as it initially appears.

    What is also important to note is that var counter is declared outside return function(name){}. As it is still being used within add : function(number){...}, this variable is accessible within that function. For failed_memoization.add()(number), it uses a new counter each time we execute that function, because we execute the first function, and then the inner function on each call. For successful_memoization.add(number) we executed the outer function upon initialization, and so counter will persist through all subsequent calls and will not be overwritten.

提交回复
热议问题