简体   繁体   English

自动分号插入:NodeJS与浏览器之间的替代转换行为?

[英]Automatic semicolon insertion: Alternate casting behavior on NodeJS vs Browser?

I have noticed different behavior in NodeJS vs. Browser while screwing around with automatic semicolon insertion and type casting. 我注意到在使用自动分号插入和类型转换时,NodeJS与浏览器的行为不同。

Browser: 浏览器:

> {}+{}
NaN
> {}+{};
NaN
> ({}+{})
"[object Object][object Object]"
> ({}+{});
"[object Object][object Object]"

NodeJS: NodeJS:

> {}+{}
'[object Object][object Object]'
> {}+{};
NaN
> ({}+{})
'[object Object][object Object]'
> ({}+{});
'[object Object][object Object]'

A. Why is casting interpreted differently with/without a semicolon or in parenthesis? A.为什么在有/没有分号或括号中对转换进行不同的解释?

B. Which is more compliant to the standard? B.哪个更符合该标准? Or is this not addressed in the standard? 还是在标准中未解决?

UPDATE: I found that it only does this different behavior in NodeJS. 更新:我发现它仅在NodeJS中执行此不同行为。 I previously thought this was V8 vs SpiderMonkey. 我以前认为这是V8 vs SpiderMonkey。

I'm going to guess that you're entering this into different debug consoles. 我猜想您正在将此输入不同的调试控制台。 One debug console treats that as a Program , and the other as an Expression . 一个调试控制台将其视为程序 ,另一调试控制台将其视为表达式


{}+{}

When interpreted as a Program this is equivalent to 当解释为程序时,它等效于

{
  // empty block
}  // No semicolon inserted because statement is a block.
(+ Number({}))  // Prefix + operator coerces its argument to a number.

When interpreted as an Expression this is equivalent to 当解释为表达式时,它等效于

// Infix + operator concatenates if arguments are not both numeric
String({}) + String({});

which coerces each object to a string and concatenates those two strings. 将每个对象强制转换为字符串,然后将这两个字符串连接起来。


Which interpreter is more compliant to the standard? 哪个口译员更符合该标准? Or is this not addressed in the standard? 还是在标准中未解决?

If, as I assume, this occurs in a debug console, then no standard addresses what a debug console has to do -- it can bypass the JavaScript interpreter entirely and interpret its input as COBOL. 如果按照我的设想,如果这发生在调试控制台中,则没有任何标准可以解决调试控制台必须执行的工作-它可以完全绕过JavaScript解释器,并将其输入解释为COBOL。

If you pass it into eval , the first interpretation must win because the argument to eval is a string that is parsed as a Program . 如果将其传递给eval ,则第一个解释必须获胜,因为eval的参数是被解析为Program的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM