If we add a method to the Number function (either a Boolean or String) like this
Number.prototype.sayMyNumber = function(){ return "My number is " + this; }
and then create a number object, assign it to a variable
var num1 = new Number(34); num1.sayMyNumber();
This is fine and expected since we created the Number object.
Similarly, if I create a primitive variable
num2 = 34; num2.sayMyNumber(); // it says "My number is 34"
Surprisingly, num2 also has a sayMyNumber () method, although it did not explicitly create a Number object.
Then I tried this,
34.sayMyNumber(); // error, this does not work
Why does num2 work?
Update
This is the next question I asked in the comments section, I put it here for better visibility.
The answers below mention that num2 is considered an internal "Number" object. This bothers me even more.
typeof num1 === "number" // returns false typeof num2 === "number" // returns true typeof num1 === "object" // returns true typeof num2 === "object" // returns false
Does this mean that num2 is not an "object"? If it is not an “object”, then how can it be an instance of “Number”?
source share