JS:在非严格模式下有两个或多个同名的对象属性?

JS: two or more object properties with the same name in non-strict mode?

阅读 David Flanagan 的权威指南(第 6 版)时偶然发现:

In strict mode, it is a syntax error for an object literal to define two or more properties by the same name. (In non-strict mode, no error occurs.)

我找不到任何示例 - 有可能吗?我试过了

var obj = {prop: 'foo', prop: 'bar'};

...但当然我最终只有一个 属性 (Object {prop: "bar"}),在严格和非严格模式下。

这个依赖于实现吗?这本书是 2011 年版,里面有 ECMAScript 5。

我应该读一本更新的书吗?

这本书是对的; ES5 规范声明在对象字面量中定义多个同名属性是语法错误。

请参阅此处 section 11.1.5

If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true

和信息丰富的Annex C

It is a SyntaxError if strict mode code contains an ObjectLiteral with more than one definition of any data property (11.1.5).

您正在测试的实现 正确,但是,由于当前的 ECMAScript 规范是 ES2015,因此取消了此限制!它未在其 Annex C 或其他任何地方列出。

如果非要我猜的话,那是因为删除的原因是与计算属性一致,所以这些文字总是等价的:

({ a: 1, ['a']: 2 })
({ a: 1, a: 2 })

但是,是的,每个人都是对的。 \o/