Sub-classing-with-extendsSection-es6-es5
by upigilam
JavaScript
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Dog extends Animal {
constructor(name) {
super(name); // call the super class constructor and pass in the name parameter
}
speak() {
console.log(this.name + ' barks.');
}
}
// ES5
/* let d = new Dog('Mitzie');
d.speak(); // Mitzie barks.
function Animal (name) {
this.name = name;
}
Animal.prototype.speak = function () {
console.log(this.name + ' makes a noise.');
}
class Dog extends Animal {
speak() {
console.log(this.name + ' barks.');
}
} */
let d = new Dog('Mitzie');
d.speak(); // Mitzie barks.