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

2016-01-06 14:23:12 +08:00
 zckevin

通过 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
})
3008 次点击
所在节点    Node.js
4 条回复
otakustay
2016-01-06 15:42:18 +08:00
V8 给力的 GC 机制,分析出这个 callback 中并不会使用 foo 和 bar ,就直接把这 2 个变量回收掉了

当然这也是正确的,你既然 callback 里不使用这 2 个变量,为啥要在意它们是什么值呢
zckevin
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
2016-01-06 16:30:22 +08:00
@zckevin V8 的 GC 注定这样,你要保留的话只能自己随便加一行
server.on('whatever', function () {
server; // 有这行就行了
debugger;
});
zckevin
2016-01-06 16:32:45 +08:00
@otakustay 嗯呢,多谢!但这样也是有些蛋疼...

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/248770

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX