Search code examples
javascriptmemoization

Memoize a prototype method


I'm trying to use memoization to speed up my Javascript, but I need it on a proto method, and I need said method to have access to the this object, and it's giving me fits. Here's what I have:

MyObj.prototype.myMethod = function(){
    var self = this
        , doGetData = (function() {
            var memo = []
            , data = function(obj) {
                var result = memo;
                if (obj.isDirty) {
                    obj.isDirty = false;
                    result = $.map(obj.details, function(elem, i) {
                        return elem.export();
                    });   
                    memo = result;                      
                }
                return result;
            }
            return data;            
        }())
    ;
    return doGetData(self);
};

I can get it to run, I just can't get it to memoize. I know something is wrong, but I can't figure out what. I know there are tons of examples of how to memoize, but none that I've come across deal with scope like this.


Solution

  • If you want the function on the prototype, but you want it to memoize for each instance independently, then "memo" needs to be an instance property (or a closure could be the instance property, I guess; whichever).

    MyObj.prototype.myMethod = function() {
      if (!("memo" in this) || this.isDirty) {
        this.isDirty =false;
        this.memo = $.map(obj.details, function(elem, i) {
           return elem.export();
        });
      }
      return this.memo;
    };
    

    I don't think you can do it without polluting the instances, though you could use newer JavaScript features to keep the "memo" thing from being enumerable. The prototype is shared by all instances, after all.