Method Borrowing

PHOTO EMBED

Wed Jun 19 2024 01:06:04 GMT+0000 (Coordinated Universal Time)

Saved by @davidmchale #this #object #method #borrowing

const davidObj = {
    first: 'David',
    last: 'Mchale',
    year: 1978,
    currentYear: new Date().getFullYear(),
    age: function () {
        const yearsold = this.currentYear - this.year;
        return yearsold;
    },
};

const maryObj = {
    first: 'Mary',
    last: 'Jones',
    year: 1985, // Add this
    currentYear: new Date().getFullYear(), // Add this
};

maryObj.age = davidObj.age;

console.log(maryObj.age()); // Output should be Mary's age




// alternative cleaner way

const davidObj = {
    first: 'David',
    last: 'Mchale',
    year: 1978,
    currentYear: new Date().getFullYear(),
    age: function (year, currentYear) {
        const yearsold = currentYear - year;
        return yearsold;
    },
};

const maryObj = {
    first: 'Mary',
    last: 'Jones',
    year: 1985,
    currentYear: new Date().getFullYear(),
};

// Borrow the age method with parameters to a function outside both objects
maryObj.age = function() {
    return davidObj.age(this.year, this.currentYear);
};

console.log(maryObj.age()); // Output should be Mary's age
content_copyCOPY

Lets us copy a method from one object to another