Skip to content

Instantly share code, notes, and snippets.

@everdimension
Last active March 5, 2020 07:59
Show Gist options
  • Select an option

  • Save everdimension/c46382933ad46456322d to your computer and use it in GitHub Desktop.

Select an option

Save everdimension/c46382933ad46456322d to your computer and use it in GitHub Desktop.
Explanation of ecmascript 6 (ES2015) classes, class inheritance, super calls and static methods. Compiled online on babel site: https://goo.gl/vfdkpC
class BaseClass {
constructor(name, age) {
this.name = name;
this.age = age;
}
static getDescription() {
return "this function can be called without instantiating BaseClass";
}
getData() {
return ["base data is:", this.name, this.age].join(' ');
}
}
let base = new BaseClass('Al Pacino', 75);
console.log(base); // logs {"name":"Al Pacino","age":75}
console.log(base.getData()); // logs "base data is: Al Pacino 75"
console.log(BaseClass.getDescription()); // *** not "base.getDescription()"
class Person extends BaseClass {
constructor(name, gender, age) {
super(name, age);
this.gender = gender;
}
speak() {
return `Hi, I'm ${this.name}. I'm ${this.age} years old and i am ${this.gender}.`;
}
getData() {
return ["person data is:", this.name, this.gender].join(' ');
}
getInfo() {
return super.getData(); // *** not "this.getData()"
}
}
let person = new Person('johny', 'male', 27);
console.log(person); // logs {"name":"johny","age":27,"gender":"male"}
console.log(person.speak()); // logs "Hi, I'm johny. I'm 27 years old and i am male."
console.log(person.getData()); // logs "person data is: johny male"
console.log(person.getInfo()); // logs "base data is: johny 27"
@timkg

timkg commented Aug 27, 2015

Copy link
Copy Markdown

Shouldn't console.log(person.getInfo()); log data is: johny 27, instead of base data is: johny 27?

@everdimension

Copy link
Copy Markdown
Author

That's correct, updated the code (line 10). Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment