Skip to content

Instantly share code, notes, and snippets.

@minmaxdata
Forked from iHani/classes.js
Created August 6, 2018 20:10
Show Gist options
  • Save minmaxdata/2a7be13c89f31dea893d40e19d0d4eed to your computer and use it in GitHub Desktop.
Save minmaxdata/2a7be13c89f31dea893d40e19d0d4eed to your computer and use it in GitHub Desktop.
Example of classes in JavaScript ES2015
class Person {
constructor(name = 'Anonymous', age = 0) {
this.name = name
this.age = age
}
getGreeting(){
return `Hi, I am ${this.name}`
}
getDescription(){
return `${this.name} is ${this.age} years old`
}
} // class Person
class Student extends Person {
constructor(name, age, major) {
super(name, age)
this.major = major
}
hasMajor() {
return !!this.major
}
getDescription(){
let description = super.getDescription()
// from this line, description will already by having the returned string
// using 'this' name & age from the super Class constructor
if (this.hasMajor()) {
description += ` Their major is ${this.major}`
}
return description
}
} // class Student
class Traveler extends Person {
constructor(name, age, homeLocation) {
super(name, age)
this.homeLocation = homeLocation
}
hasHomeLocation() {
return !!this.homeLocation
}
getGreeting(){
let description = super.getGreeting()
if (this.hasHomeLocation()) {
description += ` My homeLocation is ${this.homeLocation}`
}
return description
}
} // class Traveler
const me = new Student('Hani Y', 50, 'Computer Science')
console.log(me.getDescription());
const other = new Student()
console.log(other.getDescription());
const traveler = new Traveler('Hani Traveler', 35, 'Jeddah')
console.log(traveler.getGreeting());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment