0

To refer to this.property, there is a getter:

var foo = {
  a: 5,
  b: 6,
  get c() {
    return this.a + this.b;
  }
}

console.log(foo.c) // 11

however, is it possible to do this during object initialization:

var foo = {
  HIDING: 0,
  get state() {
    return this.HIDING;
  }
  [this.HIDING]: { x: 0, y: 0 },
}

I expect

foo: {
  HIDING: 0,
  state: 0,
  0: { x: 0, y: 0 }
}

Self-references in object literals / initializers this doesn't answer my question because it doesn't talk about using another property value as property name

nanakondor
  • 615
  • 11
  • 25
  • 2
    `this.HIDING` is undefined before the object is initialized – Luca Kiebel Jan 08 '22 at 13:22
  • 3
    oof, why does the canonical dupe target not cover this case properly... anyways, no, you cannot self-reference in an object initializer. The object is only accessible, after the initializer finished. – ASDFGerte Jan 08 '22 at 13:23
  • @ASDFGerte edit the answer? Or maybe add an answer? – Luca Kiebel Jan 08 '22 at 13:25
  • 1
    If you want "hidden" properties, you can use private class properties in a class declaration, or else create your own Symbol instances for property identifiers. – Pointy Jan 08 '22 at 13:26
  • "*Self-references in object literals / initializers this doesn't answer my question because it doesn't talk about using another property value as property name*" - see [t.j. crowder's answer](https://stackoverflow.com/a/10766107/1048572) which explains *why* it's not possible to refer to a property value before the object is created - regardless from where you try to reference it – Bergi Jan 08 '22 at 16:40
  • https://stackoverflow.com/a/4616273/5131640 - this is the original answer that made this question duplicate – Yash Kumar Verma Jan 17 '22 at 04:38
  • this is not a duplicate: they are asking about having a getter with a name that depends on another property: when `state` is `0`, they expect `foo.0` to be `{ x: 0, y: 0 }`, when `state` is `1`, they expect `foo.1` to be `{ x: 0, y: 0 }` etc. Am I right? However, I don't think it's possible because effectively this requires a getter of *any* property (since `state` may be anothing) and moreover it probably would be ill-defined (when `state` is `{a:1}`, what getter should be there?) However, this can easily be implemented as a method (`0` or `1` should be an argument) instead of a getter. – YakovL Jan 17 '22 at 07:06

1 Answers1

0

You can only do it after initialization:

var foo = {HIDING: 0};
foo[foo.HIDING] = {x: 0, y: 0};