10

I want to reference a nested property in an object literal from within another property in that same object literal.

Consider the following contrived example:

var obj = {
   product1: {
      price: 80,
      price_was: 100,
      discount: function(){

        return 100 - (100 * (price/price_was));

        //I don't want to use:  
        //100 - (100 * (this.product1.price/this.product1.price_was))
        //because the name of the parent ('product1' in this case) isn't known 
        //a-priori.

      }
   }
} 

The above is obviously incorrect, but how to get to 'price' and 'price_was' from within 'discount'?

I've looked at the following question, which is close, but in that question the needed property is a direct child of 'this', which in the above example isn't the case. reference variable in object literal?

Any way to do this?

Community
  • 1
  • 1
Geert-Jan
  • 18,623
  • 16
  • 75
  • 137
  • possible duplicate of [Self-references in object literal declarations](http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – Bergi Jan 30 '14 at 04:39

1 Answers1

4

"...in that question the needed property is a direct child of 'this', which in the above example isn't the case"

Actually, it probably is if you're calling .discount() from the productN object.

So you wouldn't use this.product1.price, because if you're calling discount from productN, then this will be a reference to productN.

Just do this:

this.price;
this.price_was;

...so it would look like:

var obj = {
   product1: {
      price: 80,
      price_was: 100,
      discount: function(){

        return 100 - (100 * (this.price/this.price_was));

      }
   }
};

Again, this assumes you're calling the function from the productN object. If not, it would be helpful if you would show how discount is being called.

user113716
  • 318,772
  • 63
  • 451
  • 440
  • 1
    That makes sense. So 'this' shifts depending on where on the object-literal you're calling from. Good to know! I will check first thing tomorrow. (I was designing on paper, when this thing popped up). BTW: how do you format 'inline code' like you did in your answer? – Geert-Jan Sep 13 '11 at 21:38
  • 1
    @Geert-Jan: Yes, but there are actually about a half-dozen ways that `this` can be set, but in the form of `obj.method()`, `this` will be set to the `obj`. The inline formatting is achieved by wrapping the \` grave accent symbol around the text. Or just select the text, and click the **`{ }`** code button at the top of the edit area, and it will wrap it for you. – user113716 Sep 13 '11 at 21:53