为什么在使用()调用Node.js REPL中的函数起作用?

JavaScript Node.js

Itachi

2020-03-23

为什么可以用经node.js测试的JavaScript调用此函数:

~$ node
> function hi() { console.log("Hello, World!"); };
undefined
> hi
[Function: hi]
> hi()
Hello, World!
undefined
> hi)( // WTF?
Hello, World!
undefined
>

为什么最后一次呼叫“” hi)(有效?是node.js中的错误,V8引擎中的错误,正式未定义的行为还是对所有解释程序实际上有效的JavaScript?

第3087篇《为什么在使用()调用Node.js REPL中的函数起作用?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
Gil 2020.03.23

4个月前针对此问题提出了一个错误https://github.com/joyent/node/issues/5698

问题在于,REPL将语句括以括号。所以

foo)(

变成

(foo)()

实际的解释可以在这里https://github.com/joyent/node/issues/5698#issuecomment-19487718找到

Mandy 2020.03.23

似乎是Node REPL错误,将这两行放在.js会导致语法错误。

function hi() { console.log("Hello, World!"); }
hi)(

错误:

SyntaxError: Unexpected token )
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3

问题已提交#6634

转载于v0.10.20。


v0.11.7已修复此问题。

$ nvm run 0.11.7
Running node v0.11.7
> function hi() { console.log("Hello, World!"); }
undefined
>  hi)(
SyntaxError: Unexpected token )
    at Object.exports.createScript (vm.js:44:10)
    at REPLServer.defaultEval (repl.js:117:23)
    at REPLServer.b [as eval] (domain.js:251:18)
    at Interface.<anonymous> (repl.js:277:12)
    at Interface.EventEmitter.emit (events.js:103:17)
    at Interface._onLine (readline.js:194:10)
    at Interface._line (readline.js:523:8)
    at Interface._ttyWrite (readline.js:798:14)
    at ReadStream.onkeypress (readline.js:98:10)
    at ReadStream.EventEmitter.emit (events.js:106:17)
> 

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android