1

Possible Duplicate:

var var1 = {};

var1.number = 20;
var1.numberplus3 = var1.number + 3;
console.log(var1.numberplus3);

var var2 = {
    number: 20,
    numberplus3: number + 3
};
console.log(var2);

In this example var1.numberplus3 evaluates to 23 but var2.numberplus3 evaluates to "undefined". Why is this?

(I am using the JS interpreter over at Codecademy: http://labs.codecademy.com/#:workspace)

Thanks!

outis
  • 75,655
  • 22
  • 151
  • 221
  • 1
    @Tomasz: That's a bit different... in this case it is a property of another object. *edit:* Oh, I was wrong... should have read the title... the code confused me, sorry. – Felix Kling Feb 26 '12 at 19:47
  • @kinakuta: Neither `var2.number` nor `this.number` will work. `var2` does not work because at that moment, `var2` is not defined yet. `this` will refer to the context of wherever the code is run (most likely `windwow`), but 100% not `var2`. – Felix Kling Feb 26 '12 at 19:57
  • Woops. Yeah I meant to write numberplus3 = var2.number + 3! That's what I actually tried to run! – Stanislav Beremski Feb 26 '12 at 20:08

1 Answers1

1

you should write like:

var var2 = {
    number: 20,
    numberplus3: function() { return var2.number + 3; }
}

or:

var var2 = {
    number: 20
};
// at this point the var2 object is defined and accessible in the memory
var2.numberplus2 = var2.number+3;
vdegenne
  • 12,272
  • 14
  • 80
  • 106
  • Aha okay...so I have to make it a function to deal with that var2 is not defined at the time that numberplus3 is being set? Presumably this is because the function in numberplus3 is evaluated only after var2 has been set? – Stanislav Beremski Feb 26 '12 at 20:05
  • @StanislavBeremski you get the idea, you trying to refer to a variable that is not accessible in the memory, look the edit. – vdegenne Feb 26 '12 at 20:12