开发者

How do I reference the same Object's properties during its creation? [duplicate]

This question already has answers here: Self-references in object literals / initializers (31 answers) Closed 5 years ago.

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.


This is ancient history now, but I just learned about getters and setters, which are perfect for your situation, and I'm sure people looking at this issue could get some value from it..

o = {
  a: { foo: 42 },
  get b() {
    return this.a
    }
  }

console.log(o.b) // => { foo: 42 }


As @RobG commented — no, you can't.

You can, however, use the this keyword inside of functions defined as properties of the object, like so:

o = {
  a: { foo: 42 },
  b: function () {
      return this.a;
  }
}

console.log(o.b()); // {foo: 42};


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.


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


Yet another way to do it:

(function() {
    var some = { foo: 42 };
    window.o = {
        a: some,
        b: some
    };
})();

alert(o.b.foo);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜