How do I reference the same Object's properties during its creation? [duplicate]
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:
- 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.
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);
精彩评论