V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
zckevin
V2EX  ›  Node.js

一个关于 Node.js debugger 作用域的问题

  •  
  •   zckevin · 2016-01-06 14:23:12 +08:00 · 2991 次点击
    这是一个创建于 3034 天前的主题,其中的信息可能已经有所发展或是发生改变。

    通过 node debug 进入 debugger ,在 repl 中打印无论 foo 还是 bar 都会报错, ReferenceError: foo is not defined 。

    var foo = 0, bar = 0
    process.nextTick(function() {
      debugger
    })
    

    但是,只要在另外一个异步回调中"使用" foo 这个变量后,再次进入 debugger ,会发现 foo 已经可以访问,然而 bar 还是 ReferenceError 。

    Google 了一会儿找不到答案...

    var foo = 0, bar = 0
    process.nextTick(function() {
      console.log(foo)
    })
    
    process.nextTick(function() {
      debugger
    })
    
    4 条回复    2016-01-06 16:32:45 +08:00
    otakustay
        1
    otakustay  
       2016-01-06 15:42:18 +08:00
    V8 给力的 GC 机制,分析出这个 callback 中并不会使用 foo 和 bar ,就直接把这 2 个变量回收掉了

    当然这也是正确的,你既然 callback 里不使用这 2 个变量,为啥要在意它们是什么值呢
    zckevin
        2
    zckevin  
    OP
       2016-01-06 16:28:38 +08:00
    @otakustay 这样啊,多谢指教!

    其实也就是想像 Python 里调试时插入一个 repl :

    ```python
    # ....

    import pdb
    pdb.set_trace()
    ```

    我的使用情景大概是这样:

    ```javascript
    var server = new Server()

    server.on('whatever', function() {
    debugger
    })

    server.listen(SERVER_PORT)
    ```

    server 上挂了一大堆状态,想要在运行时动态 inspect ,结果在 callback 里根本无法访问 server...
    otakustay
        3
    otakustay  
       2016-01-06 16:30:22 +08:00
    @zckevin V8 的 GC 注定这样,你要保留的话只能自己随便加一行
    server.on('whatever', function () {
    server; // 有这行就行了
    debugger;
    });
    zckevin
        4
    zckevin  
    OP
       2016-01-06 16:32:45 +08:00
    @otakustay 嗯呢,多谢!但这样也是有些蛋疼...
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3028 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 21ms · UTC 13:47 · PVG 21:47 · LAX 06:47 · JFK 09:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.