Last active
August 6, 2018 20:10
-
-
Save iHani/fb7fd400190da38517e8be79afaad050 to your computer and use it in GitHub Desktop.
Example of classes in JavaScript ES2015
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
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