What is the difference between a JS object literal and a JSON string?

后端 未结 6 1720
灰色年华
灰色年华 2021-02-04 19:47

I have confusion about what exactly people mean by Object Literals, JSON, JavaScript Objects, to me they seem similar:

{foo: \'bar\', bar : \'baz\'}
6条回答
  •  离开以前
    2021-02-04 20:19

    JSON is a just a data format, like XML. True JSON should have the keys surrounded by double quotes, like so:

    {"foo":"bar"}
    

    JavaScript Objects are part of the JavaScript language, and have associated things such as a prototype.

    Object literals is creating a javascript object in place with brackets as opposed to using the new keyword, or Object.create().

    //object literal
    var foo = {};
    
    //equivalent
    var foo = new Object();
    

提交回复
热议问题