javascriptfunctionobjectmethodsobject-properties

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


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?


Solution

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

    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());