英文:
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 = "foo";
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 = "foo";
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
"foo"; //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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论