JavaScript中的987和(987)有什么区别?

dfa*_*ang 8 javascript prototype

我写了一个简单的扩展方法.

Number.prototype.toMillion = function(){
 if(!Number.isNaN){
   return this/1000000;
 }
}
Run Code Online (Sandbox Code Playgroud)

987654321.toMillion() 提出:

SyntaxError:意外的标记ILLEGAL

但是(987654321).toMillion()有效.

所以我的问题是:987和之间的区别是什么(987)

仅供参考:

typeof(987) => returns "number"
Run Code Online (Sandbox Code Playgroud)

typeof((987)) still returns "number"
Run Code Online (Sandbox Code Playgroud)

Jam*_*ice 11

解析器如何知道.字符后面的部分是表示方法调用而不是数字的另一部分?例如:

10.1 // This is a number with a floating point
10.toMillion() //How does it know that this shouldn't be part of the number?
Run Code Online (Sandbox Code Playgroud)

因此,您无法在数字文字上调用方法.通过将文字放在括号(分组运算符)中,运行时将评估包含的表达式并将该方法应用于该评估的结果.

分组运算符消除了.字符的歧义.


更新

经过一些思考和对规范的一些调查后,有一个很好的理由不允许使用前瞻来确定.字符后面的内容是数字的一部分还是属性标识符.

正如评论中提到的@ CygnusX1,您可以通过使用前瞻来区分这两种情况(.后跟数字.后跟非数字字符).由于标识符不能以数字开头,如果数字字符跟随.,则必须是数字.如果跟随非数字字符.,则它不能是数字的一部分.但那不太对劲.

有一种情况,非数字字符可以跟随.字符,但仍然是数字的一部分:

console.log(1.e5); // Logs '100000'
Run Code Online (Sandbox Code Playgroud)

e指示接下来是指数,并且它可以是大写或小写.出于这个原因,使用前瞻必须考虑到如果后面的字符.eE,它仍然可以表示方法或数字的一部分.不允许在数字文字上使用属性更容易.


Tor*_*ter 5

.在JavaScript的过载.

123.123         // the interpreter assumes this is a floating point number
(123).123       // throws a syntax error, since an identifier
                // can't start with a number. - thanks James for pointing that out
(123).toMillion // refers to the function of the object returned by
                // the statement in braces
123.toMillion   // will throw a syntax error because a floating point number has only digits
Run Code Online (Sandbox Code Playgroud)