这个 JavaScript 函数如何缓存其结果?
读了好几遍后,我仍然不明白 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您已经回答了自己的问题 - 作者假设昂贵的操作会将其结果存储在
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.
结果存储在称为“缓存”的对象文字中。该代码的具体作用是:
当使用参数执行 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.
它说 // 昂贵的操作 - 推断是您在那里实现代码,将变量分配给结果 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)