why are objects wrapped in parenthesis in JS?

左心房为你撑大大i 提交于 2019-12-01 03:42:45

问题


Given the following example:

var foo = {
    root:
        ({
            key1: "Value1",
            key2: "Value2",
            key3: "Value3"
        })
    };

What is the difference compared to the following:

var foo = {
    root:
        {
            key1: "Value1",
            key2: "Value2",
            key3: "Value3"
        }
    };

In the first example there is an additional parens wrapping the object. What purpose does this serve? Does it have anything to do with scoping? Does it influence the execution in any way? Thank you!


回答1:


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.




回答2:


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




回答3:


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}]


来源:https://stackoverflow.com/questions/12509311/why-are-objects-wrapped-in-parenthesis-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!