0
function person(name,age) {
this.name = name;
this.age = age;

let birthday = function() {
    return new Date().getFullYear() - this.age;
 }

this.data = function() {
    return this.name + " "+this.age + ' birthday: ' + birthday();
 }
}    

const l = new person('JOhn', 24); console.log(l.data());// NaN `

Why the value of this.age is NaN and what I should do?

ssilas777
  • 9,672
  • 4
  • 45
  • 68
  • Hi, Roman Azimi! Where is `age` coming from? – HoldOffHunger May 20 '20 at 15:16
  • Apart from this being a duplicate, try to learn modern javascript instead of year long obsolete code – baao May 20 '20 at 15:18
  • @HoldOffHunger age is a property of constructor that its value is assigned when we instantiated a new object from the constructor . – Roman Azimi May 20 '20 at 15:18
  • I can see that. This is just a function, not a constructor. The code that is calling this function is not defining `age`. That is likely your problem. The code that calls the function, not the function. – HoldOffHunger May 20 '20 at 15:21
  • No it's not @HoldOffHunger. The problem is that they try to access the outer `this` in a function that has his own `this`, with no property age in there. – baao May 20 '20 at 15:22
  • Ah, good point, too. Roman Azimi: Try that, try removing all this.var references, and just use the params as they're passed, `return name + " " + `, etc... – HoldOffHunger May 20 '20 at 15:24
  • @HoldOffHunger Just read the linked answer and search for other `this` posts on SO and the internet. Your last recommendation is also false. `name` is undefined – baao May 20 '20 at 15:25

0 Answers0