[英]function statement's strange behavior when inspecting node.js in chrome devtools
I use chrome devtools to debug node.js script ( node --inspect script.js
, as described eg in https://nodejs.org/en/docs/guides/debugging-getting-started/ ) 我使用chrome devtools调试node.js脚本(
node --inspect script.js
,如https://nodejs.org/en/docs/guides/debugging-getting-started/中所述 )
For some reason a function statement is not working properly. 由于某种原因,功能语句无法正常工作。 This is the code:
这是代码:
function f(){};
f=1;
console.log(f);
http = require('http');
myserver=http.createServer(function (req, res) {
res.end();
}).listen(8080);
The console outputs 1
, but then when I try to enter f
in the console it says "Uncaught ReferenceError: f is not defined". 控制台输出
1
,但是当我尝试在控制台中输入f
时,它显示“ Uncaught ReferenceError:f未定义”。
If instead of a function statement I use function expression, everything works well: 如果我使用函数表达式代替函数语句,则一切正常:
f=function(){};
f=1;
console.log(f);
http = require('http');
myserver=http.createServer(function (req, res) {
res.end();
}).listen(8080);
So I wonder what is the source of the problem and how to fix it. 因此,我想知道问题的根源是什么以及如何解决它。
PS The createServer part of the script is a trick I use so that the chrome devtools console is still running after the script has been executed. PS:脚本的createServer部分是我使用的一个技巧,因此在脚本执行后chrome devtools控制台仍在运行。 By the way, is there any more straightforward way to do it?
顺便说一句,还有其他更直接的方法吗?
Update: I stumbled upon an alternative way which does not have this problem with function statement: node --inspect -e "$(< script.js)"
更新:我偶然发现了另一种方法,该方法在函数语句中没有此问题:
node --inspect -e "$(< script.js)"
The first script declares are local variable in the module scope, which is initialised with the function, then assigned with 1
, then garbage collected - the server closure doesn't use it, see Why does Chrome debugger think closed local variable is undefined? 第一个脚本声明的是模块范围内的局部变量,该局部变量先用函数初始化,然后分配给
1
,然后进行垃圾回收-服务器关闭未使用它,请参阅Chrome调试器为何认为闭合的局部变量未定义? . 。
The second script does not declare any variable 1 , it does assign to a global 2 . 第二个脚本未声明任何变量1 ,而是将其分配给全局变量2 。 First the function, then the value
1
, but global variables cannot get garbage-collected as any code that runs later might still access them. 首先是函数,然后是值
1
,但是全局变量无法被垃圾回收,因为稍后运行的任何代码仍可以访问它们。
[1]: Using var f
would probably lead the the same result as with the first script. [1]:使用
var f
可能会导致与第一个脚本相同的结果。
[2]: Always "use strict"
mode ! [2]:始终
"use strict"
模式 ! You would have gotten a proper exception. 您将获得适当的例外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.