Node.js REPL在函数声明或函数expression式之后自动声明下划线?

今天我发现了一些关于node.js的奇怪现象:

$ node > console.log(_) ReferenceError: _ is not defined at repl:1:13 at REPLServer.defaultEval (repl.js:130:27) at bound (domain.js:257:14) at REPLServer.runBound [as eval] (domain.js:270:12) at REPLServer.<anonymous> (repl.js:277:12) at REPLServer.EventEmitter.emit (events.js:107:17) at REPLServer.Interface._onLine (readline.js:202:10) at REPLServer.Interface._line (readline.js:531:8) at REPLServer.Interface._ttyWrite (readline.js:812:14) at ReadStream.onkeypress (readline.js:101:10) > function foo() {} undefined > console.log(_) undefined undefined 

我创build一个函数expression式后发生同样的事情:

 $ node > console.log(_) ReferenceError: _ is not defined at repl:1:13 at REPLServer.defaultEval (repl.js:130:27) at bound (domain.js:257:14) at REPLServer.runBound [as eval] (domain.js:270:12) at REPLServer.<anonymous> (repl.js:277:12) at REPLServer.EventEmitter.emit (events.js:107:17) at REPLServer.Interface._onLine (readline.js:202:10) at REPLServer.Interface._line (readline.js:531:8) at REPLServer.Interface._ttyWrite (readline.js:812:14) at ReadStream.onkeypress (readline.js:101:10) > (function () {}()) undefined > console.log(_) undefined undefined 

这是非常酷的,方便你故意要作为undefined函数参数,但为什么会发生? 我在Arch Linux上使用节点版本v0.11.13

这是repl的一个特性: _返回最后一个expression式的结果。

当然,在某些情况下 – 比如说console.log – expression式不会返回结果。 但是,是获得最后一个expression式的价值的一个方便的方法。

这只发生在REPL当然 – 如果你input相同的节点程序并从一个文件运行, _将在你的控制之下。