0

I'm using an object structure for my js file and want to be able to assign one of the properties (which is an array) to one of the other properties:

AvGen = {

    theBody: {
        bodies: [
            fooObj,
            foo2Obj,   // <--- assign this property...
            foo3Obj
        ],
        bodyColor: '#DB6EDB',
        currBodyNr: 1,
        currBodyObj: AvGen.theBody.bodies[1]    // <--- ...to this property

// ... rest of the code

However, when trying to do it I get the following error message:

Uncaught ReferenceError: AvGen is not defined

If I remove 'AvGen' it says that 'theBody' isn't defined instead. How can I accomplish this?

holyredbeard
  • 19,619
  • 32
  • 105
  • 171

3 Answers3

1

In newer browsers you could use a getter:

AvGen = {

    theBody: {
        bodies: [
            1,
            2,
            3
        ],
        bodyColor: '#DB6EDB',
        currBodyNr: 1,
        get currBodyObj() {
           return AvGen.theBody.bodies[AvGen.theBody.currBodyNr];
        }
    }
}

console.log(AvGen.theBody.currBodyObj); //2

FIDDLE

But you could also just use a method instead of a property:

currBodyNr: 1,
currBodyObj: function() {
   return AvGen.theBody.bodies[AvGen.theBody.currBodyNr];
}

//...

console.log(AvGen.theBody.currBodyObj()); //2
basilikum
  • 10,378
  • 5
  • 45
  • 58
0

You'd have to initialize the object AvGen first so that it takes the set values of bodies and then, through a function assign the one you want to this.currBodyObj.

Giovanni Di Toro
  • 797
  • 1
  • 14
  • 34
0

Avgen isn't instantiated yet on that line. Instead, do this:

AvGen = {};
AvGen.theBody = {};
AvGen.theBody.bodies = [fooObj, foo2Obj, foo3Obj];
AvGen.theBody.bodyColor = '#DB6EDB';
AvGen.theBody.currBodyNr = 1;
AvGen.theBody.currBodyObj = AvGen.theBody.bodies[1];
// etc..
rgthree
  • 7,217
  • 17
  • 21