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

标签 javascript node.js

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

创建函数表达式后会发生同样的事情:

$ 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

这非常酷,并且对于您有意将其保留为 未定义 的函数参数来说非常方便,但为什么会发生这种情况呢?我在 Arch Linux 上使用 Node 版本 v0.11.13

最佳答案

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

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

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

关于javascript - Node.js REPL 在函数声明或函数表达式后自动声明下划线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25701665/

相关文章:

javascript - 异步箭头函数的语法错误

Node.js - 如何使用回调调用异步函数?

node.js - 将 AWS EB 平台版本从 2.0.1 升级到 3.1.0

javascript - 如何查找 HTMLElement 是否包含在所选文本中

javascript - 使用 React 绘制 d3 轴,无需直接操作 D3 DOM

javascript - 当我的 props 发生变化时,如何在 Svelte 中强制重新渲染?

javascript - 无法使用http模块nodejs azure函数执行http请求

javascript - React中的Select不反射(reflect)状态变化

javascript - JQuery-UI ToolTip 位置

node.js - ExpressJS如何构建应用程序?