Search code examples
jqueryobjectpropertiesobject-literal

Use a variable in object property


I use object literal for my js, and below you can see it's "global" variables. One of them is an object (theBody) which in turn contains of an array called 'bodies'. This array contains of several objects (just one in the example below), which are svg objects.

I want to be able to assign the fill value from a specific variable, called bodyColor but when I change:

'fill':'#e59225',

to

'fill': AvGen.theBody.bodyColor,

I get the error Uncaught ReferenceError: theBody is not defined

Why is that and how can I access bodyColor for the object property?

from the js:

var AvGen = {

    paper: null,
    theBody: {
        bodies: [
            [0,0,277.9,308.5,{
                type:'path',
                'fill':'#e59225',
                'stroke':'none',
                'stroke-width':'0',
                'fill-opacity':'1',
                'stroke-opacity':'0'
            }],
        ],
        currNr: 1,
        currObj: null,
        bodyColor: '#e59225'
    },

    init: function() {

    }
}

Solution

  • You're trying to refer to something before it has already been defined! You're trying to use theBody and it hasn't been created yet. You can do something like this instead:

    var AvGen = {
        paper: null,
        theBody: {
            bodies: [
                [0,0,277.9,308.5,{
                    type:'path',
                    'fill': null,
                    'stroke':'none',
                    'stroke-width':'0',
                    'fill-opacity':'1',
                    'stroke-opacity':'0'
                }],
            ],
            currNr: 1,
            currObj: null,
            bodyColor: '#e59225'
        },
    
        init: function() {
    
        }
    }
    
    AvGen.theBody.bodies[0][4].fill = AvGen.theBody.bodyColor;
    

    Or even better; extract bodyColor out completely:

    var bodyColor = "#e59225";
    var AvGen = {
        paper: null,
        theBody: {
            bodies: [
                [0,0,277.9,308.5,{
                    type:'path',
                    'fill': bodyColor,
                    'stroke':'none',
                    'stroke-width':'0',
                    'fill-opacity':'1',
                    'stroke-opacity':'0'
                }],
            ],
            currNr: 1,
            currObj: null,
            bodyColor: bodyColor
        },
    
        init: function() {
    
        }
    }