Confused about a Javascript closure case
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 ca开发者_如何学Cche = 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?
I think you want this:
function getCollection(collectionName) {
var cache;
return function(callback) {
instead of what you have right now:
function getCollection(collectionName) {
return function(callback) {
var cache;
Nothing closes over cache
after the function returned from getCollection
(usersCollection
) executes. There is no function that is returned from that scope.
cache
needs to be defined outside of the usersCollection
function for any reference to it to be captured.
精彩评论