如何在创建过程中引用相同的Object属性? [英] How do I reference the same Object's properties during its creation?
问题描述
我正在尝试像
o = {
a: { foo: 42 },
b: o.a
}
但是返回错误,表示o未定义。我知道我以后可以做o.b = o.a.但是我想知道在我定义o时是否可以定义b。
But that returns an error saying o is not defined. I know I can later do o.b = o.a. But I'm wondering if it's possible to define b while I'm in defining o.
推荐答案
这是不可能的。
在评估属性值时,对象不会绑定到EcmaScript表达式可见的任何范围内。
The object is not bound in any scope visible to EcmaScript expressions when the property values are evaluated.
Section < ecmaScript语言规范的href =http://es5.github.com/#x11.1.5 =noreferrer> 11.1.5 解释了对象构造函数语法的工作原理。
Section 11.1.5 of the EcmaScript language spec explains how the object constructor syntax works.
下面描述如何创建对象作为评估第一个属性键值对的副作用
The following describes how the object is created as a side-effect of evaluating the first property key value pair
生产
PropertyNameAndValueList:PropertyAssignment
评估如下:
- 让 obj 是创建一个新对象的结果,好像是通过表达式
new Object()
其中Object
是具有该名称的标准内置构造函数。 - 让 propId 成为e的结果评估 PropertyAssignment 。
- 使用参数
propId.name调用 obj 的[[DefineOwnProperty]]内部方法
,propId.descriptor
,false
。 - 返回 obj 。
- Let obj be the result of creating a new object as if by the expression
new Object()
whereObject
is the standard built-in constructor with that name. - Let propId be the result of evaluating PropertyAssignment.
- Call the [[DefineOwnProperty]] internal method of obj with arguments
propId.name
,propId.descriptor
, andfalse
. - Return obj.
请注意 PropertyAssignment <在创建 obj 之后评估/ em>,但 obj 永远不会绑定到EcmaScript表达式可访问的任何名称。
Note that PropertyAssignment is evaluated after obj is created, but obj is never bound to any name accessible to an EcmaScript expression.
只有在评估了所有属性值之后,才会分配给 o
或程序中的任何其他符号。
Only after all the property values are evaluated is anything assigned to o
or any other symbol in your program.
这篇关于如何在创建过程中引用相同的Object属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!