立即访问对象的属性 [英] Immediately accessing an object's property

查看:64
本文介绍了立即访问对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出这四个定义对象然后尝试立即访问其属性的示例:

Given these four examples of defining an object and then attempting to immediately access their properties:

{foo: 'bar'}.foo
// syntax error: unexpected_token

我预计这将返回值'foo',但它会导致语法错误。

I expected this would return the value of 'foo', but it results in a syntax error.

我能想到的唯一解释是对象定义尚未执行,因此尚未执行一个东西。因此似乎忽略了对象定义,并且语法错误来自于尝试执行:

The only explanation I can come up with is that the object definition hasn't been executed and therefore is not yet an object. It seems that the object definition is therefore ignored and the syntax error comes from attempting to execute just:

.foo
// results in the same syntax error: unexpected_token

同样:

{foo: 'bar'}['foo']
// returns the new Array ['foo']

这似乎证明了对象文字被忽略并且执行了尾随代码。

Which seems to be evidence that the object literal is ignored and the trailing code is executed.

然而,这些工作正常:

({foo: 'bar'}).foo
// 'bar'

({foo: 'bar'})['foo']
// 'bar'

括号用于运行代码行,由于该括号运算符的结果是实例化对象,因此可以访问属性。

The parentheses are used to run the line of code and since the result of that parenthetical operator is the instantiated object, you can access properties.

那么,为什么忽略对象定义而不立即执行?

So, why is the object definition ignored and not executed immediately?

推荐答案

这是一个问题对于上下文,你的前两个例子不是对象文字!

It's a matter of the "context", your first two examples are not object literals!

它们是语句块,例如:

{ foo: 'bar' }

以上代码被评估为一个块,包含标签声明 foo )指向表达式语句(字符串文字'bar')。

The above code is evaluated as a block, containing a labelled statement (foo) that points to an expression statement (the string literal 'bar').

当您将它包装在括号上时,代码将在表达式上下文中进行评估,因此语法与Object Literal语法匹配。

When you wrap it on parentheses, the code is evaluated in expression context, so the grammar matches with the Object Literal syntax.

实际上还有其他方法可以强制进行表达式求值,你会看到 dot 属性访问符号在直接应用于对象文字时有效,例如: / p>

In fact there are other ways to force the expression evaluation, and you will see that the dot property accesor notation works when applied directly to an object literal e.g.:

({foo:'bar'}.foo);  // 'bar'
0, {foo:'bar'}.foo; // 'bar'
0||{foo:'bar'}.foo; // 'bar'
1&&{foo:'bar'}.foo; // 'bar'
// etc...

现在在你的第二个例子中:

Now in your second example:

{foo: 'bar'}['foo']

这里发生的是评估两个语句,首先是块,然后是包含Array文字的表达式语句。

What happens here is that the two statements are evaluated, first the block and then the expression statement that contains the Array literal.

语法模糊度与函数表达式与函数声明类似。

Is a syntax ambiguity similar to what happens with function expressions vs function declarations.

参见:

  • SyntaxError or no SyntaxError

这篇关于立即访问对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆