Snippets Collections
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
star

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

#this #object #method #borrowing

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension