Why are JavaScript primitives not instanceof Object?

前端 未结 1 600
忘掉有多难
忘掉有多难 2021-01-05 02:24

Today I happened to have too much time to kill and I played a bit with the Node (v0.10.13) command line:

> 1 instanceof Object
false
> (1).__proto__
{}         


        
相关标签:
1条回答
  • 2021-01-05 03:00

    You have been tricked by a mechanism commonly known as "boxing" (c# related article, java related article) which mesmerises all who come across it. You had the correct answer in the beginning:

    Perhaps because 1 is a primitive not an object to begin with?

    Exactly so. However, how can primitives ever be able to contain methods? How can they contain properties? After all, in js, they are represented at the lowest level possible (see #4.3.2). To make these values actually useful, whenever you do primitive.property, the following happens (#11.2.1):

    Object(primitive).property;
    

    In other words, js has automatic boxing. This can be proven using one of my favourite tricks:

    var primitive = 'food';
    primitive.isPizza = true; //yummy
    console.log(primitive.isPizza); //undefined. where did my pizza go!?
    

    primitive.isPizza disappeared because of this boxing:

    var primitive = 'food';
    Object(primitive).isPizza = true;
    console.log(Object(primitive).isPizza);
    

    The boxed primitive is its own unique snowflake - when you box it a second time, it does not refer to the same thing. The boxed values are quickly GCd and forgotten in the mists of time.

    This does not happen if your primitive isn't, well, a primitive:

    var obj = new String('food');
    obj.isPizza = true;
    console.log(obj.isPizza); //true
    

    Does this mean you should only use objects, never primitives? Nope, for the simple reason that the times you do need to store meta-data on primitives are very far and few, and objects complicate things:

    obj === primitive; //false, obj is an object, primitive is a primitive
    
    0 讨论(0)
提交回复
热议问题