[英]Why does calling a function in the Node.js REPL with )( work?
為什么可以用這樣的JavaScript調用函數,用node.js測試:
~$ node
> function hi() { console.log("Hello, World!"); };
undefined
> hi
[Function: hi]
> hi()
Hello, World!
undefined
> hi)( // WTF?
Hello, World!
undefined
>
為什么最后一次調用, hi)(
,工作?是node.js中的bug,V8引擎中的bug,官方未定義的行為,還是所有解釋器的實際有效JavaScript?
這是由於REPL如何評估輸入,最終是:
(hi)()
添加附加括號以強制它為表達式 :
// First we attempt to eval as expression with parens.
// This catches '{a : 1}' properly.
self.eval('(' + evalCmd + ')',
// ...
目的是將{...}
視為Object
文字/ 初始化而不是塊 。
var stmt = '{ "foo": "bar" }';
var expr = '(' + stmt + ')';
console.log(eval(expr)); // Object {foo: "bar"}
console.log(eval(stmt)); // SyntaxError: Unexpected token :
並且,正如leesei所提到的,這已經改為0.11.x, 它將只包裝{ ... }
而不是所有輸入:
if (/^\s*\{/.test(evalCmd) && /\}\s*$/.test(evalCmd)) {
// It's confusing for `{ a : 1 }` to be interpreted as a block
// statement rather than an object literal. So, we first try
// to wrap it in parentheses, so that it will be interpreted as
// an expression.
evalCmd = '(' + evalCmd + ')\n';
} else {
// otherwise we just append a \n so that it will be either
// terminated, or continued onto the next expression if it's an
// unexpected end of input.
evalCmd = evalCmd + '\n';
}
似乎是一個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)
>
4個月前有一個錯誤,針對此問題https://github.com/joyent/node/issues/5698
問題是因為,REPL用parens包含了這些陳述。 所以
foo)(
變
(foo)()
可在此處找到實際說明https://github.com/joyent/node/issues/5698#issuecomment-19487718 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.