Kedkedders Kedkedders - 3 months ago 7
Javascript Question

How to access an object value within the same object

I have a JavaScript object, and I need some of the properties to reference values of other properties. Namely, I have a button that I want to sit relative to the parent panels position at all times, this is what I tried:

var main_panel_obj = {
id: 'mainPanel',
component: 'Window',
draggable: false,
padding: 4,
position: { x: 0, y: 0 },
width: gW*.04,
height: gH,
layout: [1, 3],
children: [
{
id: 'btnWater',
component: 'Button',
skin: 'bluebutton',
position: { x: this.position.x, y: this.position.y+20 }, // x,y from line 6
width: gW * 0.03,
height: gH * 0.03
}
]
};


How do I get the child button's position to refer to the parent's panel pos?

Answer

Either hard-code them again (since this is all one statement in the code anyway so they can't have changed):

position: { x: 0, y: 20 }

Or declare them first with variables and then use the variables:

var startX = 0;
var startY = 0;
var main_panel_obj = {
    //...
    position: { x: startX, y: startY },
    //...
    children: [
    {
        //...
        position: { x: startX, y: startY + 20 },
        //...
    }]
};

An object has no knowledge of another object which holds a reference to it. After all, what would happen if multiple objects held a reference to it?

Comments