Search code examples
javascriptprototypeprimitive

Confusion about prototype chain , primitives and objects


in firebug console :

>>> a=12 
12
>>> a.__proto__
Number {}
>>> (12).__proto__
Number {}
>>> a.constructor.prototype === (12).__proto__
true
>>> a.constructor.prototype.isPrototypeOf(a)
false

the final line causes me a great confusion as compared to the other lines. also see Constructor.prototype not in the prototype chain?


Solution

  • When you use the . operator with a primitive, the language auto-boxes it with the appropriate Object type (in this case, Number). That's because simple primitive types in JavaScript really are not Object instances.

    Thus, the actual left-hand side of

    a.__proto__
    

    is not the number 12 but essentially new Number(12). However, the variable "a" continues to be the simple number value 12.

    editSection 8.7 of the spec "explains" this with typical ECMA 262 moon language. I can't find a clear paragraph that describes the way that a primitive baseValue is treated as a Number, Boolean, or String instance, but that section directly implies it. I think that because those non-primitive synthetic values are ephemeral (they're only "real" while the . or [] expression is being evaluated) that the spec just talks about the behavior without explicitly requiring that an actual Number is constructed. I'm guessing on that however.