Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is this JavaScript function caching its results?

After reading over it several times, I still don't understand how this example code from page 76 of Stoyan Stefanov's "JavaScript Patterns" works. I'm not a ninja yet. But to me, it reads like it's only storing an empty object:

var myFunc = function (param) {
  if (!myFunc.cache[param]) {
    var result = {};
    // ... expensive operation ...
    myFunc.cache[param] = result;
  } 
  return myFunc.cache[param];
};
// cache storage
myFunc.cache = {};

Unless that unseen "expensive operation" is storing back to result, I don't see anything being retained.

Where are the results being stored?

P.S.: I've read Caching the return results of a function from John Resig's Learning Advanced JavaScript, which is a similar exercise, and I get that one. But the code is different here.

like image 644
parisminton Avatar asked Feb 24 '23 03:02

parisminton


1 Answers

You've answered your own question -- the author assumes that the expensive operation will store its result in result.

The cache would otherwise only contain empty objects, as you've noted.

like image 85
Cameron Avatar answered Feb 26 '23 23:02

Cameron