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

时间:2014-09-06 15:12:11

标签: javascript node.js

我今天发现了一些关于node.js的奇怪之处:<​​/ p>

$ 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

1 个答案:

答案 0 :(得分:2)

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

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

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