0

JavaScript learner here: given this object:

var ivan = {
    name: 'Ivan',
    yearOfBirth: 1973,
    age: 2017 - this.yearOfBirth
}

console.log(ivan.age);

Why the console.log says NaN? Can't I do simple math operations in property declaration? if not, why?

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Ivan
  • 2,463
  • 6
  • 39
  • 51

1 Answers1

1

That happen since this.yearOfBirth is not defined yet, You could use anonymous function as a constructor :

var ivan = new function() {
    this.name = 'Ivan',
    this.yearOfBirth = 1973,
    this.age = 2017 - this.yearOfBirth
};
console.log(ivan.age);
halfer
  • 19,824
  • 17
  • 99
  • 186
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • Thanks, the solution is too advanced for me at the moment (I'm following a Javascript course) but I think I got the explanation: so, when I define the object, "this" doesn't exists yet... it starts existing when I "use" somehow the object, right? – Ivan Dec 02 '17 at 19:35
  • Oh, and more: "this" can be used only inside object methods, right? Using it on properties like my not-working example is a mess,as it turns out, isn't it? – Ivan Dec 02 '17 at 19:40