Prototypes

Each objects in JavaScript has a prototype.

// Object.prototype
// Person.prototype

function Person(firstName, lastName, dob){
    this.firstName = firstName;
    this.lastName = lastName;
    this.birthday = new Date(dob);
    
}

// Calculate age - Prototype method
Person.prototype.calculateAge = function(){
    const diff = Date.now() - this.birthday.getTime();
    const ageDate = new Date(diff);
    return Math.abs(ageDate.getUTCFullYear() - 1970);
}

// Get full name - Prototype method
Person.prototype.getFullName = function(){
    return `${this.firstName} ${this.lastName}`;
}

// Gets Married
Person.prototype.getsMarried = function(newLastName){
    this.lastName = newLastName;
}

const gabor = new Person('Gabor', 'Flamich', '1984-11-24');
const john = new Person('John', 'Dow', '1990-08-12');
const erika = new Person('Erika', 'Swanson', '1970-12-09');

console.log(john.calculateAge());

console.log(erika.getFullName());

erika.getsMarried('Smith');

console.log(erika.getFullName());

console.log(erika.hasOwnProperty('firstName'));
console.log(erika.hasOwnProperty('getFullName'));
Was this page helpful?

Reader Interactions

Leave a Reply

Your email address will not be published. Required fields are marked *