Skip to content

Instantly share code, notes, and snippets.

@SanjeQi
Last active August 4, 2020 16:13
Show Gist options
  • Save SanjeQi/507420b0db7c173732bd90c0db144178 to your computer and use it in GitHub Desktop.
Save SanjeQi/507420b0db7c173732bd90c0db144178 to your computer and use it in GitHub Desktop.
Classes and subClasses ES6
////////////////////////////////////////////////////Classes and subClasses
//ES5
var Person5 = function (name, yearOfBirth, job) {
this.name = name;
this.yearOfBirth = yearOfBirth;
this.job = job;
};
Person5.prototype.calcAge = function () {
var age = new Date().getFullYear() - this.yearOfBirth;
console.log('ES5: ', age);
};
var Athlete5 = function (name, yearOfBirth, job, olympicGames, medals) {
Person5.call(this, name, yearOfBirth, job);
this.olympicGames = olympicGames;
this.medals = medals;
};
Athlete5.prototype = Object.create(Person5.prototype);
Athlete5.prototype.wonMedals = function () {
this.medals++;
console.log(this.medals);
};
var johnAthlete5 = new Athlete5('John', 1990, 'swimmer', 3, 10);
johnAthlete5.calcAge();
johnAthlete5.wonMedals();
// ES6
class Person6 {
constructor(name, yearOfBirth, job) {
this.name = name;
this.yearOfBirth = yearOfBirth;
this.job = job;
}
calcAge() {
const age = new Date().getFullYear() - this.yearOfBirth;
console.log('ES6: ', age);
}
}
class Athelete6 extends Person6 {
constructor(name, yearOfBirth, job, olympicGames, medals) {
super(name, yearOfBirth, job);
this.olympicGames = olympicGames;
this.medals = medals;
}
wonMedals() {
this.medals++;
console.log(this.medals);
}
}
const johnAthlete6 = new Athelete6('John', 1990, 'cyclist', 2, 10);
johnAthlete6.calcAge();
johnAthlete6.wonMedals();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment