The primitive type Number has a corresponding object representation, which you can create with new Number
. This is an object and is therefore of a different data type than the primitive type Number.
If you call Number(34)
(without new
) an object isn't created, but the Number function performs a type conversion, to a primitive number value.
var num1 = new Number(34); // object
var num2 = 34; // primitive
When you call sayMyNumber()
on the primitive number num2
, JavaScript internally converts the primitive temporarily to its equivalent object version. And because you added sayMyNumber()
to Number.prototype
you have access to the function.
The reason 34.sayMyNumber()
doesn't work is because when JavaScript engine parses your source code, it has to interpret just what a dot means in a given context. In the case of 34.sayMyNumber()
the dot is potentially ambiguous. Does it mean the decimal separator? Or does it mean object member access? JavaScript opts to interpret all integers followed by a dot as representing part of a floating point number. But as there is no such number 34.sayMyNumber(), it raises a SyntaxError. Read more here