对 Javascript 闭包案例感到困惑
我正在使用node-mongodb 驱动程序编写一些node.js 代码。我决定在获取集合对象时缓存它们,如下所示:
var db = connectionObject;
function getCollection(collectionName) {
return function(callback) {
var cache;
if (cache) return callback(null, cache);
db.collection(collectionName, function(err, collection) {
return err ? callback(err) : callback(null, cache = collection);
});
}
}
var usersCollection = getCollection('users');
usersCollection(function(err, collection) {
collection.find({}); // Rest of code here ...
});
重复调用 usersCollection 函数应该使用缓存的集合对象,但事实并非如此 - 缓存变量始终未定义。将代码更改为此可以解决问题:
return function(callback) {
var cache = arguments.callee;
if (cache.cached) return callback(null, cache.cached);
db.collection(collectionName, function(err, collection) {
return err ? callback(err) : callback(null, cache.cached = collection);
});
}
我仍然对为什么“cache”变量超出范围感到困惑。我做错了什么?
I am writing some node.js code using the node-mongodb driver. I decided to cache the collection objects when I obtain them like this:
var db = connectionObject;
function getCollection(collectionName) {
return function(callback) {
var cache;
if (cache) return callback(null, cache);
db.collection(collectionName, function(err, collection) {
return err ? callback(err) : callback(null, cache = collection);
});
}
}
var usersCollection = getCollection('users');
usersCollection(function(err, collection) {
collection.find({}); // Rest of code here ...
});
Repeated calls of the usersCollection function should use the cached collection object, except that it doesn't - the cache variable is always undefined. Changing the code to this fixes the problem:
return function(callback) {
var cache = arguments.callee;
if (cache.cached) return callback(null, cache.cached);
db.collection(collectionName, function(err, collection) {
return err ? callback(err) : callback(null, cache.cached = collection);
});
}
I am still confused about why the 'cache' variable goes out of scope. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想你想要这个:
而不是你现在拥有的:
I think you want this:
instead of what you have right now:
从
getCollection
(usersCollection
) 返回的函数执行后,cache
上的任何内容都不会关闭。该作用域没有返回任何函数。cache
需要在usersCollection
函数之外定义,以便捕获对它的任何引用。Nothing closes over
cache
after the function returned fromgetCollection
(usersCollection
) executes. There is no function that is returned from that scope.cache
needs to be defined outside of theusersCollection
function for any reference to it to be captured.