对Javascript闭包案件感到困惑

dis*_*cer 1 javascript closures mongodb node.js

我正在使用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 ...
});
Run Code Online (Sandbox Code Playgroud)

对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);
    });
}
Run Code Online (Sandbox Code Playgroud)

我仍然对'cache'变量超出范围的原因感到困惑.我究竟做错了什么?

Ion*_*tan 5

我想你想要这个:

function getCollection(collectionName) {
    var cache;
    return function(callback) {
Run Code Online (Sandbox Code Playgroud)

而不是你现在拥有的:

function getCollection(collectionName) {
    return function(callback) {
        var cache;
Run Code Online (Sandbox Code Playgroud)

  • @Discodancer - 不,它不会 - 每次调用"getCollection()"都会有自己的"缓存"变量. (2认同)