The reason is that in this statement:
var Josh = {
dateOfBirth: 1990,
age: calculateAge(this.dateOfBirth),
}
this
does not refer to Josh
, or to the object that will become Josh
. There's no way it could, because none of these things exist yet when this statement executes.
In this statement this
refers to whatever it refers to in any other statement in that scope.
console.log(this); // <-- same this
var Josh = {
dateOfBirth: 1990,
age: calculateAge(this.dateOfBirth), // <-- same this
}
console.log(this.someProperty); // <-- same this
If the this
in that scope doesn't have a dateOfBirth
property of 1990
, you're not going to get the result you're expecting.
If you want to avoid having to repeat the 1990
value, then store it in a variable, and reference that variable:
var dob = 1990;
var Josh = {
dateOfBirth: dob,
age: calculateAge(dob)
};