如何在创建过程中引用相同对象的属性? [英] How do I reference the same Object's properties during its creation?

查看:33
本文介绍了如何在创建过程中引用相同对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做类似的事情

o = {a: { foo: 42 },b: o.a}

但这会返回一个错误,指出 o 未定义.我知道我以后可以做 o.b = o.a.但是我想知道是否可以在定义 o 的同时定义 b.

解决方案

这是不可能的.

在评估属性值时,对象未绑定在 EcmaScript 表达式可见的任何范围内.

EcmaScript 语言规范的 11.1.5 部分解释了对象构造函数语法的工作原理.

下面描述了如何创建对象作为评估第一个属性键值对的副作用

<块引用>

产生式 PropertyNameAndValueList : PropertyAssignment 计算如下:

  1. obj 成为创建新对象的结果,就好像通过表达式 new Object() 其中 Object 是标准构建的 -在具有该名称的构造函数中.
  2. propId 成为评估 PropertyAssignment 的结果.
  3. 使用参数 propId.namepropId.descriptorfalse 调用 obj 的 [[DefineOwnProperty]] 内部方法.
  4. 返回对象.

请注意,PropertyAssignment 在创建 obj 之后进行评估,但 obj 永远不会绑定到 EcmaScript 表达式可访问的任何名称.>

只有在评估完所有属性值后,才会分配给 o 或程序中的任何其他符号.

I'm trying to do someting like

o = {
  a: { foo: 42 },
  b: o.a
}

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.

解决方案

It is not possible.

The object is not bound in any scope visible to EcmaScript expressions when the property values are evaluated.

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

The production PropertyNameAndValueList : PropertyAssignment is evaluated as follows:

  1. Let obj be the result of creating a new object as if by the expression new Object() where Object is the standard built-in constructor with that name.
  2. Let propId be the result of evaluating PropertyAssignment.
  3. Call the [[DefineOwnProperty]] internal method of obj with arguments propId.name, propId.descriptor, and false.
  4. Return obj.

Note that PropertyAssignment is evaluated after obj is created, but obj is never bound to any name accessible to an EcmaScript expression.

Only after all the property values are evaluated is anything assigned to o or any other symbol in your program.

这篇关于如何在创建过程中引用相同对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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