Why do you need to add parentheses when adding a prototype method to Number in Javascript?
给我你的怀抱
给我你的怀抱 2017-05-19 10:18:07
0
2
634

Directly call the method on the Number prototype, as follows:

10.toString();

An error will be reported: Uncaught SyntaxError: Invalid or unexpected token

However, there will be no error if you call floating point numbers directly

10.1.toString();//"10.1"

I saw this explanation:
Number literals directly call methods. As long as the JavaScript engine does not confuse the decimal point and the dot operator of the object, various writing methods can be used, and JavaScript will understand the first point. into a decimal point (i.e. 10.0), and understand the second point as calling the object property to get the correct result.

For example, the following calling methods are correct

(10).toString(2)
10..toString(2) // "1010"
10 .toString(2) // "1010"
10.0.toString(2) // "1010"
10['toString'](2) // "1010"

But I don’t understand the working principle here.
I initially guessed that it was due to the priority of the bracket or dot operator. Did I convert 10 to number first?
But I don’t think this can be explained.

Could you please tell me why an error occurs when calling prototype methods directly on integers, but not on floating point numbers?
Why can the prototype method of an integer be called through the methods listed above?

给我你的怀抱
给我你的怀抱

reply all(2)
世界只因有你

I saw this explanation: Numeric literals directly call methods. As long as the JavaScript engine does not confuse the decimal point with the dot operator of the object, various writing methods can be used. JavaScript will understand the first point as a decimal point (i.e. 10.0), understand the second point as calling object properties, so as to obtain the correct result.

My opinion: As long as the meaning of the dot is unambiguous, the compiler can understand it correctly.

(10).toString(2) // "1010"

Obviously the brackets are added and the following .点运算符

10..toString(2) // "1010"

There is no number with two decimal points, so this also refers to 点运算符

So this 10..toString(2) can actually be boiled down to the following

10.0.toString(2) // "1010"

The point after the floating point number must no longer refer to the decimal point, but to 点运算符

10['toString'](2) // "1010"

obj[key] This way you can find the attribute named key in obj.

10.toString() Reason for error

The reason is that the compiler will have two interpretations when seeing this:

1. (10.0).toString(); 
2.  10   .toString(); 
phpcn_u1582

Compilation principle, when the engine starts to parse numbers, . is legal, so it will be given priority as a decimal point. The above solutions all tell the parser "finished reading the numbers" and start reading the next token.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!