JavaScript: Object.prototype.toString(new Number(5)) seems to return a wrong type

77 views Asked by At

I am writing JavaScript interpreter in Python and I have to understand internals. Consider this code (tested on V8):

Object.prototype.toString(new Number(5)) //gives "[object Object]"

According to the specification of Number constructor:

"The [[Class]] internal property of the newly constructed object is set to "Number"."

And Object.prototype.toString returns the combination of:

"[object ", class, and "]" // where class is the value of [Class]] internal property of O.

Therefore why the returned value is "[object Object]" instead of "[object Number]"? Is it a bug in V8 or my understanding is wrong?

1

There are 1 answers

2
jjm On BEST ANSWER

toString doesn't take an argument -- it's a method on the object. So if you call Object.prototype.toString.call(new Number(5)) (thus passing the Number instance as this) you'll get the expected result: [object Number].

You get similarly bogus results when calling SomeClass.prototype.toString with an argument, for example Number.prototype.toString(new Number(5)) will give '0'.

I tested all of this on node (which uses v8).