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

前端 未结 4 659
闹比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  { ...}
    

提交回复
热议问题