Skip to content Skip to sidebar Skip to footer

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 som

Solution 1:

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

Solution 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


Post a Comment for "Javascript Object Literal Referring To Another Property In Itself From Another Property"