Last active
September 12, 2020 07:39
-
-
Save TheFoot/f98f968bf582fd79fae498dfb94d4d18 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Sample ES6 classes | |
*/ | |
/** Implement private methods using symbols*/ | |
const _braceFood = Symbol ( 'braceFood' ); | |
// Base class | |
class Being { | |
constructor ( name, eyes = 2 ) { | |
this.type = 'being'; | |
this.name = name; | |
this.eyes = eyes; | |
// Increment static counter | |
Being.count++; | |
} | |
// Getter/setters | |
set eats ( food ) { | |
this.food = food; | |
} | |
get favouriteMeal () { | |
return `${this.name} prefers ${this[ _braceFood ] ()}.`; | |
} | |
// Public methods | |
sayHi () { | |
return `${this.name} grunts`; | |
} | |
canJudgeDistance () { | |
return this.eyes >= 2; | |
} | |
// Static getter | |
static get howManyBeings () { | |
return Being.count; | |
} | |
// Private method | |
[ _braceFood ] () { | |
return this.food || 'nothing'; | |
} | |
} | |
// Static Being properties | |
Being.count = 0; | |
// Human class - extending the base Being class | |
class Human extends Being { | |
/** Class constructor */ | |
constructor ( name ) { | |
// Call base constructor | |
super ( name, 2 ); | |
this.type = 'human'; | |
} | |
// Override method | |
sayHi () { | |
return `${super.sayHi ()} and says hi!`; | |
} | |
describeMyself () { | |
return `${this.sayHi ()} I am a ${this.type}, and I have ${this.eyes} - I can${this.canJudgeDistance () ? '' : 'not'} judge distance.` + | |
` For dinner, I prefer to eat ${this.favouriteMeal}.`; | |
} | |
} | |
// Export all classes | |
module.exports = { | |
Being, | |
Human | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment