0
var a={b:44,c:this.b+1};

I want c to be b+1 or 45 in this case. but when I try this, I get Cannot read property 'b' of undefined error.

1 Answers1

0

In JavaScript, when creating an object, the execution context doesn't change. Hence, the this value is picked up from the top-level in your case. Or to articulate in a different way, you can't access the properties of the object if it's not finished initializing yet.

The actual solution to your problem might be:

var a = { b: 44 };
a.c = a.b + 1;
radiantshaw
  • 535
  • 1
  • 5
  • 18
  • Does not answer the question. An alternate solution makes sens if you will provide expected one first. – ulou May 22 '21 at 12:16
  • @ulou Should I change the word "alternate" to something else? Cause now that you say it, it doesn't feel like an alternate solution, but a different way to solve the problem. – radiantshaw May 22 '21 at 12:19
  • It's not what OP wanted and that's `Or to articulate in a different way, you can't access the properties of the object if it's not finished initializing yet.` not even true. Post is already closed and marked as duplicate. – ulou May 22 '21 at 12:21
  • @ulou `not even true` Just out of curiosity, I know that the object properties can be accessed inside getters, but how else is my statement false? – radiantshaw May 22 '21 at 12:27