Created
March 28, 2022 18:41
-
-
Save mkastner/c08d49094428d8ddcf950f485f5cd1f5 to your computer and use it in GitHub Desktop.
Composition/Inheritance JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Part I: objects and composition | |
const Person = { | |
set givenName(givenName) { | |
this._givenName = givenName; | |
}, | |
set familyName(familyName) { | |
this._familyName = familyName; | |
}, | |
fullName() { | |
return `${this.givenName} ${this.familyName}`; | |
}, | |
}; | |
const Customer = Object.assign( | |
{}, // create a new object by extending prototype Person | |
Person, | |
// add score prop for and doubleScore function for customer | |
{ | |
set score(score) { | |
this._score = score; | |
}, | |
doubleScore() { | |
return this.score * 2; | |
}, | |
} | |
); | |
const Employee = Object.assign( | |
{}, // create a new object by extending prototype Person | |
Person, | |
// add salary prop and bonus function for employee | |
{ | |
set salary(salary) { | |
this._salary = salary; | |
}, | |
bonus() { | |
return this.salary * 0.2; | |
}, | |
} | |
); | |
// Part II: implemenation | |
const john = Object.create(Customer); | |
john.givenName = 'John'; | |
john.familyName = 'Doe'; | |
john.score = 100; | |
const jane = Object.create(Customer); | |
jane.givenName = 'Jane'; | |
jane.familyName = 'Doe'; | |
jane.score = 155; | |
const jack = Object.create(Employee); | |
jack.givenName = 'Jack'; | |
jack.familyName = 'Black'; | |
jack.salary = 1000; | |
const jill = Object.create(Employee); | |
jill.givenName = 'Jill'; | |
jill.familyName = 'White'; | |
jill.salary = 1200; | |
console.log('Customer fullName :', john.fullName()); | |
console.log('Customer doubleScore:', john.doubleScore()); | |
console.log('Customer fullName :', jane.fullName()); | |
console.log('Customer doubleScore:', jane.doubleScore()); | |
console.log('Employee fullName :', jack.fullName()); | |
console.log('Employee bonus :', jack.bonus()); | |
console.log('Employee fullName :', jill.fullName()); | |
console.log('Employee bonus :', jill.bonus()); | |
console.log('Check john prototype for Customer', Object.getPrototypeOf(john) === Customer); | |
console.log('Check john prototype for Employee', Object.getPrototypeOf(john) === Employee); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment