这个 JavaScript 函数如何缓存其结果?

发布于 2024-11-09 05:12:39 字数 720 浏览 0 评论 0原文

读了好几遍后,我仍然不明白 Stoyan Stefanov 的“JavaScript”第 76 页的示例代码是如何实现的模式” 有效。我还不是忍者。但对我来说,它读起来就像只存储一个空对象:

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

除非那个看不见的“昂贵的操作”存储回结果,否则我看不到任何内容被保留。

结果存储在哪里?

PS:我读过 缓存 John Resig 的《学习高级 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 = {};

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

七婞 2024-11-16 05:12:39

您已经回答了自己的问题 - 作者假设昂贵的操作会将其结果存储在 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.

孤千羽 2024-11-16 05:12:39

结果存储在称为“缓存”的对象文字中。该代码的具体作用是:

当使用参数执行 myFunc 时,该函数首先检查缓存。如果缓存中有“param”的值,则返回该值。如果没有,则执行昂贵的操作,然后缓存结果(以参数为键),因此下次使用相同参数调用该函数时,将使用缓存。

the results are being stored in the object literal called 'cache'. What the code is specifically doing is:

when myFunc gets executed with a param, the function first checks the cache. If there is a value for 'param' in the cache, it returns it. If not, you do the expensive operation, and then cache the result(with param as the key), so the next time the function is called with the same param the cache is used.

北城挽邺 2024-11-16 05:12:39

它说 // 昂贵的操作 - 推断是您在那里实现代码,将变量分配给结果 var,或将结果 var 设置到另一个对象(这是昂贵操作的结果)

It says // expensive operation - the inference is that you implement code there which assigns variables into the result var, or sets the result var to another Object (which is the result of an expensive operation)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文