JAVASCRIPT: Getting NaN result after calling function in document.write()

85 Views Asked by At

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?

3

There are 3 best solutions below

0
trincot On BEST ANSWER

You did not create an instance of person, and you did not call a property of that instance:

  • bornYear references this, which seems intended to be a person instance, so you must bind this to it somehow.
  • As you defined a property yearOfBirth, it would be appropriate to call that method.

Also, your bornYear function is limited to the year 2020. You should take the current year, using the Date constructor.

Here is how it could work:

function person(name, age){
    this.name = name;
    this.age = age;
    this.yearOfBirth = bornYear.bind(this); // bind this
}
function bornYear(){
    // Use the current year to calculate year of birth
    return new Date().getFullYear() - this.age;
}
// First create an instance, then call the method
document.write(new person("Helen", 18).yearOfBirth());

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.write is bad practice in this scenario. Use console.log.

The standard way would go like this:

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    bornYear() {
        return new Date().getFullYear() - this.age;
    }
}
console.log(new Person("Helen", 18).bornYear());

0
cbalakus On

Try this:

function bornYear(){
    return 2020 - parseInt(this.age);
}
0
Brother Woodrow On

You seem to be mixing up object oriented programming with a functional style of programming. If you want to use this like you're doing, you'd have to do something like:

function Person(name, age) {
    this.name = name;
    this.age = age;
    this.yearOfBirth = () => {
        return new Date().getFullYear() - this.age;
    };
}
let newPerson = new Person('Foo', 25);
document.write(newPerson.yearOfBirth());