6

I have a object literal:

var obj = {
    a : document.getElementById("ex1"),
    b : obj.a.document.getElementsByTagName("div")
};

I am having trouble with the b property, for some reason it is not letting that happen. Is this possible?

bryan sammon
  • 6,821
  • 12
  • 36
  • 46
  • possible duplicate of [Self-references in object literal declarations](http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – zzzzBov Jun 18 '13 at 20:29

3 Answers3

3

The modern way to do this is with getter methods:

let obj = {
  firstName: "A’dab",
  lastName: "Farooqi"
  get fullName() {
    return this.firstName+" "+this.lastName;
  },
}

So now you can just write obj.fullName - no need for the parentheses on the end.

  • This should be accepted as the corrected answer, given the most recent updates of the JavaScript. Also, this his a powerful feature that should be more disseminated among developers. – Almir Campos Apr 16 '20 at 11:34
2

You need two steps:

var obj = {
    a : document.getElementById("ex1")
};

obj.b = obj.a.document.getElementsByTagName("div")

Or:

var temp = document.getElementById("ex1")
var obj = {
    a : temp,
    b : temp.document.getElementsByTagName("div")
};
Tomasz Nurkiewicz
  • 324,247
  • 67
  • 682
  • 662
2

When the property b is being defined, obj is not defined yet. One way to get around that problem is to make your property a function so that it's not evaluated until called.

var obj = {
    a : document.getElementById("ex1"),
    b : function() {
      // This is not evaluated until obj.b() is called
      return obj.a.document.getElementsByTagName("div");
    }
};
obj.b();

If you really want it to be a property, you have to do it in two steps as Tomasz Nurkiewicz shows

Community
  • 1
  • 1
Juan Mendes
  • 85,853
  • 29
  • 146
  • 204
  • You could use a [getter method](https://developer.mozilla.org/en/JavaScript/Reference/Operators/get) in browsers that support it `var obj={a:document.getElementById("ex1"),get b(){return this.a.document.getElementsByTagName("div")}};` – user123444555621 Feb 16 '12 at 19:38
  • @Pumbaa80 By browsers that support it, you mean Firefox only??? A better approach would be to use `Object.defineProperty` since it's available in the latest version of all browsers, but that also requires multiple steps – Juan Mendes Feb 16 '12 at 20:09
  • 1
    Actually, [all browsers but IE<=8 support it](http://robertnyman.com/javascript/javascript-getters-setters.html#regular-getters-and-setters). Browser support for `defineProperty` is the same. – user123444555621 Feb 16 '12 at 20:43