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

时间:2021-05-19 22:28:12

I found out something weird about node.js today:

我今天发现了一些关于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

The same thing happens after I create a function 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

It's pretty cool, and handy for function arguments which you intentionally want to leave as undefined, but why does it happen? I am using node version v0.11.13 on Arch Linux.

它非常酷,并且对于您有意想要保留为未定义的函数参数很方便,但为什么会发生?我在Arch Linux上使用节点版本v0.11.13。

1 个解决方案

#1


2  

It's a feature of the repl: _ returns the result of the last expression.

它是repl的一个特性:_返回最后一个表达式的结果。

Of course, in some cases - like the console.log you have - an expression will not return a result. But yeah it's a handy way to get the value of the last expression.

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

This only happens in the REPL of course - if you type up the same node program and run it from a file, _ will be under your control.

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

#1


2  

It's a feature of the repl: _ returns the result of the last expression.

它是repl的一个特性:_返回最后一个表达式的结果。

Of course, in some cases - like the console.log you have - an expression will not return a result. But yeah it's a handy way to get the value of the last expression.

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

This only happens in the REPL of course - if you type up the same node program and run it from a file, _ will be under your control.

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