0

I have this code with me,

var x = {
  a: 10,
  b: 20,
  c: (this.a + this.b)
};

where this.a and this.b is coming as undefined. So as a result of adding the both and printing it displays NaN. Also I tried with (x.a + x.b). The results were the same.

Can anyone tell how do I access a JSON object's value internally using this? May be other way?

Mediocre
  • 281
  • 2
  • 9
  • you can't do like this if you want achieve you can make c as function : var x = { a: 10, b: 20, c: function(){ return (this.a + this.b); } }; x.c(); – Sundar Singh Jan 25 '16 at 06:38
  • `this` doesn't refer to `x` in this case, it refers to the global object. – little pootis Jan 25 '16 at 06:38
  • Thank you so much. I will refer the linked question to know more. Actually I did not have the exact words to frame a search query for this problem. – Mediocre Jan 25 '16 at 06:39
  • @SundarSingh Thanks sundar. That may be a good idea to achieve what I wanted. – Mediocre Jan 25 '16 at 06:40

1 Answers1

0

Better way to using the same object value in JSon using "this"

 var x = {
   a: 10,
   b: 20,
   c: function(){return (this.a + this.b)}
 };
 console.log(x.c())
Sandeeproop
  • 1,756
  • 1
  • 12
  • 18