JavaScript对象文字不起作用

时间:2018-04-05 20:10:16

标签: javascript parsing object literals

这是JavaScript object literals中的错误,至少是解析器吗?



////////// a bug in JavaScript? //////////

// works:
const pointless = {
  "a b": 1,
  "c": 2
};

// works:
({
  "a b": 1,
  "c": 2
});

// fails when uncommented:
// {
//   "a b": 1,
//   "c": 2
// };

////////// what lead to the above //////////

// works:
class Thing {
  static get table() {
    return {
      'x': function () { console.log('You chose x!') },
      'y': function () { console.log('You chose y!') }
    };
  }
    
  static doAllTheThings(arg) {
    this.table[arg]();
  }
}

Thing.doAllTheThings('x');

// works:
function doAllTheThings(arg) {
  ({
    'x': function () { console.log('You chose x!') },
    'y': function () { console.log('You chose y!') }
  })[arg]();
}

doAllTheThings('y');

// fails when uncommented:
// function doAllTheThings(arg) {
//   {
//     'x': function () { console.log('You chose x!') },
//     'y': function () { console.log('You chose y!') }
//   }[arg]();
// }

// doAllTheThings('y');




现场演示:https://repl.it/repls/DeadlyFatherlyVertex

我偶然发现了这个尝试制作跳转表而不是使用巨型切换命令。将{}包裹在()中,但恕我直言不是必需的。

它有这样的原因吗?

1 个答案:

答案 0 :(得分:1)

当您使用()围绕{}时,您正在创建一个表达式,该表达式就是对象的评估方式。

但是,您也可以通过简单地使用{}在JavaScript中创建一个空范围(仍然与周围范围相关联),因此您认为对象的内部实际上被解释为代码,在"a b" : 1,失败,这是一行无效的代码。



{
    console.log(1);
}




相关问题