这个JavaScript函数如何缓存其结果? [英] How is this JavaScript function caching its results?

查看:89
本文介绍了这个JavaScript函数如何缓存其结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过几次阅读,我仍然不明白 Stoyan的第76页的示例代码如何Stefanov的"JavaScript模式" 有效.我还不是忍者.但是对我来说,它看起来就像是只存储一个空对象:

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 = {};

除非将看不见的昂贵的操作"存储回result,否则我看不到保留任何内容.

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

结果存储在哪里?

PS:我已阅读

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.

推荐答案

您已经回答了自己的问题-作者假设昂贵的操作会将其结果存储在result中.

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.

这篇关于这个JavaScript函数如何缓存其结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆