2014-09-06 45 views
2

今天我发现了一个很奇怪的关于Node.js的:Node.js REPL在函数声明或函数表达式后自动声明下划线?

$ 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 

同样的事情发生后,我创建了一个函数表达式:

$ 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

+0

''当您试图使用需要'_'的代码作为下划线库时,整个'_'事情令人stag目结舌。变通办法很拙劣,并不真正起作用;我重新编译,以摆脱它 - 我不使用它.'' – 2014-09-06 15:29:19

+0

@DaveNewton但不是repl假设只有当你通过命令行使用节点时才工作?不是在程序本身?我很困惑,因为我在REPL文档中发现了“通过执行没有任何命令行参数的节点,您将被放入REPL”这一行。 – 2014-09-06 15:39:10

+0

+1以及注意到此功能。我不会知道或询问这件事。 – 2014-09-06 15:40:41

回答

2

这是the repl的功能:_返回最后一个表达式的结果。

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

这只发生在REPL当然 - 如果您键入相同的节点程序并从文件运行它,_将在您的控制之下。