I'm trying to get the bornYear as the result with the below code but getting NaN as a result.
function person(name, age){
this.name = name;
this.age = age;
this.yearOfBirth = bornYear;
}
function bornYear(){
return 2020 - this.age;
}
document.write(bornYear());
What I'm missing here?
You did not create an instance of
person, and you did not call a property of that instance:bornYearreferencesthis, which seems intended to be apersoninstance, so you must bindthisto it somehow.yearOfBirth, it would be appropriate to call that method.Also, your
bornYearfunction is limited to the year 2020. You should take the current year, using theDateconstructor.Here is how it could work:
It is more common to define such a method on the prototype though, and to start the constructor name with a capital (
Person).Also, using
document.writeis bad practice in this scenario. Useconsole.log.The standard way would go like this: