0

I have an object like:

var foo = {
   a: {
      b: ... || ... || ... || 30
   }
 , c: bar(... || ... || ... || 30)
};

Is it possible to access foo.a.b key instead of writing again ... || ... || ... || 30 in the bar call?

I also can do:

foo.c = bar(foo.a.b);

But I would choose a shorter way if possible.

I tried to do bar(this.a.b) that doesn't work (Cannot read property 'b' of undefined.).

Ionică Bizău
  • 93,552
  • 74
  • 254
  • 426
  • error message? you're at 14.5k rep, don't you know to post what went wrong instead of "that doesn't work"? – djechlin Aug 12 '14 at 05:15
  • Nop, `this` depends on how the function that uses it gets called; no function there. – elclanrs Aug 12 '14 at 05:15
  • @djechlin The error message is `Cannot read property 'b' of undefined`. I thought it can be simply guesssed. :-) – Ionică Bizău Aug 12 '14 at 05:17
  • @elclanrs Yes, this is not in a function block... – Ionică Bizău Aug 12 '14 at 05:18
  • Sure, but that error message exactly tells you the problem is not where you think it is. You brushed it aside as unimportant (given away by your not posting it); however it was crucial. If you didn't understand the message better to google it. – djechlin Aug 12 '14 at 05:20
  • As an alternative I suggest `var v = ... || ... || ... 30; var foo = {a: {b: v}, c: bar(v)};` – Felix Kling Aug 12 '14 at 05:26

1 Answers1

0

Yes, of course.

Your error means this.a is undefined, just like {}.foo would be undefined, and {}.foo.bar would throw an error like undefined.bar would throw an error. You can try all this in a console (browser or Node.js).

this will bind to the object in a member function (in a pseudo-class), but usually to the global object. (The rules are complicated - please learn them). Without seeing your full code I can't tell, but it really looks like this will not refer to foo.

djechlin
  • 54,898
  • 29
  • 144
  • 264