why are objects wrapped in parenthesis in JS?

后端 未结 3 1087
隐瞒了意图╮
隐瞒了意图╮ 2020-12-17 00:57

Given the following example:

var foo = {
    root:
        ({
            key1: \"Value1\",
            key2: \"Value2\",
            key3: \"Value3\"
               


        
相关标签:
3条回答
  • 2020-12-17 01:04

    There is absolutely no difference here.

    AFAIK the one place where it does make a difference is when you evaluate an object literal on the console.

    0 讨论(0)
  • 2020-12-17 01:12

    They do nothing :) They're there for readability, although it's questionable if they achieve that aim.

    0 讨论(0)
  • 2020-12-17 01:23

    As per me, we should use square brackets to collect the objects. because, JavaScript will understand that it is an array.

    Round brackets(used in example 1) are just validated by the javasript parser. When you try to access it, java script returns Only last object in the round brackets(like top object in the stack).

    Try below script

    var foo = {
        root1:
            {
                key1: "Value1",
                key2: "Value2",
                key3: "Value3"
            },
        root2:({
                key4: "Value4",
                key5: "Value5"
              },{
                key6: "Value6",
                key7: "Value7"
            }),
        root3:[
             {
                key8: "Value8",
                key9: "Value9"
              },{
                key10: "Value10",
                key11: "Value11"
              }
        ]
        };
        console.log(foo['root1']);  // returns object { key1, key2, key3}
        console.log(foo['root2']);  // returns only { key6,key7}
        console.log(foo['root3']);  //returns [ {key8,key9},{key10,key11}]
    
    0 讨论(0)
提交回复
热议问题