在node.js中函数返回后丢失值的对象

时间:2015-08-08 09:53:04

标签: javascript node.js debugging scope v8

对于node.js中的部分路由应用程序,我有一些结构如下:

module.exports = function Router(){
    var self = this;`
    var ROUTES = {
        "GET": {},
        "POST": {},
        "PATCH": {},
        "DELETE": {}
    };

    self.get = function(path, action){
        return compile_route_listing (path, action, method);
    };

    // this is how I view the routing listings outside of the debugging call below
    self.list = function(){
        console.log(ROUTES);
    };

    function compile_route_listing(path, action, method){
        if(path_valid(path) && action_valid(action)){
            var parts = action.split ("#"); // -> [controller, action]
            var qualifier = new RegExp (compile_route_regex(path), "i");
            var handle   = new ActionHandle (parts[0], parts[1]);
            ROUTES[method][path] = {
                "qualifier": qualifier,
                "handle": handle
            };
            console.log(ROUTES); // debugging call, does same thing as self.list
            return true;
        } else {
            // throws my errors, not relevant here
        }
    };

}; // end Router()

我遇到的问题是在compile_route_listing函数内部,调试console.log(ROUTES)调用显示

{ "GET": {"my_path":
                { "qualifier": /some valid regex/i,
                  "action": [object ActionHandler] }
         },
  "POST": {},
  "PATCH": {},
  "DELETE": {}
}

...但是一旦compile_route_listing函数返回,对上面产生上述内容的console.log(ROUTES)的完全相同的调用现在产生(这次是通过self.list()方法):

{ "GET": {"my_path":
                { "qualifier": {},
                  "action": {} }
         },
  "POST": {},
  "PATCH": {},
  "DELETE": {}
}

有效对象似乎已被空对象替换/覆盖。

我的第一个想法是他们超出范围,所以我尝试将编译功能更改为

function compile_route_listing(path, action, method){
    if(path_valid(path) && action_valid(action)){
      var parts = action.split ("#"); // -> [controller, action]
      var qualifier = compile_route_regex(path); // just a string
      var handle   = parts; // just an array ["controller", "action"]
      ROUTES [method][path] = {
        "qualifier": qualifier,
        "handle": handle
         };
       console.log(ROUTES); // debugging call, does exact same thing as self.list
       return true;
     } else {
       // throws my errors, not relevant here
     }
   };

并且对console.log(ROUTES)的内部调用和通过self.list()的外部调用返回为:

{ "GET": {"my_path":
                { "qualifier": "uncompiled regex string",
                  "action": ["controller", "action"] }
         },
  "POST": {},
  "PATCH": {},
  "DELETE": {}
}

我不明白为什么类型String和Array最后通过函数返回但实例化的RegExp和我的自定义ActionHandler对象被重置为空白状态。

我真的很感激帮助理解造成这种情况的潜在机制是什么......我花了几个小时在网上搜索,并且没有找到解决方案的运气。提前谢谢。

-Jake

编辑1
在评论中提到我没有说明我如何访问函数范围之外的值,所以我尽力修改帖子的原始语言以使其清楚。

我目前正在对路由列表的创建进行单元测试,所以我还没有继续实现与路由处理程序交互的功能。我还在努力确保它们正确保存到ROUTES对象,这就是问题所在。

0 个答案:

没有答案