{x}.x 单独使用时为什么会报错,但在表达式中却不会?

huangapple go评论75阅读模式
英文:

Why does the expression {x}.x throw error by itself, but within an expression it doesn't?

问题

{a}.a 会导致错误。

英文:

I have been reading about object initialization on mdn and came across the following example:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const a = &quot;foo&quot;;
const b = 42;
const c = {};

// Shorthand property names
const o = { a, b, c };

// In other words,
console.log(o.a === { a }.a); // true

<!-- end snippet -->

What is surprising to me is that {a}.a gives error by itself:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const a = &quot;foo&quot;;
const b = 42;
const c = {};

// Shorthand property names
const o = { a, b, c };

// In other words,
console.log(o.a === { a }.a); // true

console.log({a}.a); // all good
&quot;foo&quot;; //all good
//but the following gives error
{a}.a; 

<!-- end snippet -->

答案1

得分: 1

=== 后面的 { 表示开始一个对象初始化器,用于创建一个对象。

你可以在一个对象后面加上 .a 来访问它的属性。


{ 开头的语句是一个

你不能在块后面加上 .a。这没有意义。

英文:

A { after === starts an object initilizer which creates an object.

You can put .a after an object to access a property of it.


A statement that starts with a { is a block.

You can't put a .a after a block. It doesn't make sense.

huangapple
  • 本文由 发表于 2023年6月27日 19:12:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76564274.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定