简体   繁体   中英

Javascript Object Literal referring to another property in itself from another property

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?

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")
};

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM