Tuesday, 19 July 2022

Constructor and this keyword example

function Person(fName, lName, dob)

{ 

   this.fName=fName;

   this.sName=lName;

   this.fullName=function(){

       return this.fName+' '+this.sName;

     }

   this.calculateAge=function(){

      const   var dob = new Date(dob);

    //calculate month difference from current date in time

    const month_diff = Date.now() - dob.getTime();

    //convert the calculated difference in date format

    const age_dt = new Date(month_diff); 

    //extract year from date    

    const year = age_dt.getUTCFullYear(); 

    //now calculate the age of the user

    const age = Math.abs(year - 1970); //here 1970 not hardcoded value instead normal way of caculating the age , but weird 😁!

    return  age;

   }

}