Why does `{foo: 1}` evaluate to `1` in the console, and `{foo: 1, bar: 2}` results in an error?

前端 未结 4 658
闹比i
闹比i 2020-12-21 09:03

I knew that {} is either an object or a block of code, but today my co-worker asked me why {foo: 1} works when entered into the console, but

相关标签:
4条回答
  • 2020-12-21 09:26

    {} not block always, you can make an object with it (JSON style) for example

    var objectName = {
        propertyName:"Fiat", 
        model:500, 
        color:"white",
        methodName:function(a) {
            return a;
        }
    };
    
    objectName.methodName('aa');
    
    objectName.propertyName
    
    objectName[propertyName]
    

    and they're blocks

    if(...){ .. }
    while(...) { ... }
    try(..) { ...} catch  { ...}
    
    0 讨论(0)
  • 2020-12-21 09:37

    It all depends on context:

    function test() {
       var foo = {a:1}; // this is an object
       { alert('Hi mom!'); } // this is a block of code
       { a: 1 }; // also just a block of code, but `a:` is a label
    }
    

    If the {} block is used in an (in)equality test (==, ===, !=, etc...) or an assignment (=), then it's an object. All other contexts would be "just a block of code".

    0 讨论(0)
  • 2020-12-21 09:39

    By itself, {a: 1} is a block statement, where a is a label.

    Of course, in a context where an expression is expected, it is an object literal:

    var o = { a: 1 };
    
    0 讨论(0)
  • 2020-12-21 09:45

    i'm sorry not to comment under your post due to lack of reputation.

    can you elaborate more on "Why I can print foo: 1 in JavaScript"?

    If I run this code

    var t = {foo: 1};
    

    It will become the property for object "t". The same behaviour will be implement if you use this code

    var t = {foo: 1, bar: 2};
    

    You can access it by "t.foo" and "t.bar" and it will return the value either "1" or "2".

    You can read the explanation of "object" here JavaScript Objects

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