Why [object Object] mentions “object” twice?

后端 未结 4 2139
孤独总比滥情好
孤独总比滥情好 2020-12-09 07:30

[object Object] is the default string representation of a JavaScript Object.

I would understand if it was just [Object] or [object], but wh

相关标签:
4条回答
  • 2020-12-09 08:00

    I would understand if it was just [Object] or [object], but why [object Object]?

    Because it is an object created from the basic Object class.

    From the spec:

    Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".


    Is it part of JSON or JavaScript?

    It has absolutely nothing to do with JSON.

    0 讨论(0)
  • 2020-12-09 08:08

    All objects have a toString method that displays something in the format [object type], where type is the object type.

    When called on null you get [object Null] and when called on an object you get the string [object Object] because it's based on the Object constructor (capital "O"), that's why it says object twice, it's an object of the type Object.

    MDN

    JSON is a lightweight data-interchange format, and doesn't really have anything to do with JavaScript other than being named "JavaScript Object Notation" because it's written like a JavaScript object.

    0 讨论(0)
  • 2020-12-09 08:15

    The first object denotes that the type of the thing being logged is an object. It's also hard-coded in the language specification here.

    The second Object denotes the constructor property, for example:

    Object.prototype.toString.call(""); // [object String]
    

    The algorithm just says: "Get the [[class]] property of the object and then return '[object ' + class + ']'.

    0 讨论(0)
  • 2020-12-09 08:17

    You've basically hit the platonic wall end of the cave. If everything is an object, what is the superset of object? Here, the answer is embodied in the code, it is simply object.

    Hence all Objects are objects.

    Welcome to the circularity.

    0 讨论(0)
提交回复
热议问题