1

I was writing a javascript object and to prevent duplication of aliases of the same object

For example, repeating the key for the same values here:

var colours = {
    red: {
        rgb: "255,0,0",
        hex: "#FF0000"
    },
    brickred: {
        rgb: "255,0,0",
        hex: "#FF0000"
    }
};

I tried making a reference to the same object, instead to avoid duplication:

var colours = {
    red: {
        rgb: "255,0,0",
        hex: "#FF0000"
    },
    brickred: this.red
};

However, this does'nt work. I realised (I think) this is because it refers to the window object and not colours. So then I tried:

var colours = {
    red: {
        rgb: "255,0,0",
        hex: "#FF0000"
    },
    brickred: colours.red
};

But this still doesn't work and I don't understand why. How can I solve this?

N.B. The example isn't very good, but basically I have an object literal and want to avoid duplication where I have different keys with same value. I'd also like to know why it doesn't work for curiosity

user2521439
  • 1,405
  • 2
  • 13
  • 19
  • possible duplicate of [Javascript literal object, reference to itself](http://stackoverflow.com/questions/8347770/javascript-literal-object-reference-to-itself). See also http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations or http://stackoverflow.com/questions/4858931/reference-variable-in-object-literal or https://www.google.co.uk/?q=object%20literal%20reference%20self%20javascript – Matt Feb 19 '14 at 19:48

2 Answers2

5

Because at the point of creation the object (including its red key) doesn't exist yet. You can add it afterwards, though:

var colours = {
    red: {
        rgb: "255,0,0",
        hex: "#FF0000"
    }
};

colours.brickred = colours.red;
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
1

I think for you're specific example it might be simpler to encapsulate the object in a separate variable and then apply it to the object, like this:

var _RED = { 
  rgb:"255,0,0", 
  hex:"#ff0000" 
}

var colours = {
  red: _RED,
  brickred: _RED
}

Also, not really what you want for a few reasons, but you could change brickred to a function then you can use this in the manner you originally tried:

var colours = {
    red: {
      rgb: "255,0,0",
      hex: "#FF0000"
    },
    brickred: function() { return this.red; }

};

In this case you could never change the values of brickred and it would have to be called like a function instead of accessed like an attribute, i.e. colours.brickred(). It will always return whatever red is set to.

George Mandis
  • 791
  • 1
  • 4
  • 18