I'm learning about creating a new class, extending it and subclassing. I don't understand the following:
- Why in extending the class in example #2 both the
constructor()and thesuper()uselengthas an argument? - If
super()in example #2 is supposed to access the parent class Polygon, shouldn't it use as argumentsheightandwidthto access them in the Polygon class instead oflength(like it does in example #4)? If not, why?
Source code is: https://googlechrome.github.io/samples/classes-es6/index.html
// Example 1: Creating a new class (declaration-form)
// ===============================================================
class Polygon {
constructor(height, width) {
this.name = 'Polygon';
this.height = height;
this.width = width;
}
sayName() {
console.log('Hi, I am a ', this.name + '.');
}
sayHistory() {
console.log('"Polygon" is derived from the Greek polus (many) ' +
'and gonia (angle).');
}
}
// Example 2: Extending an existing class
// ===============================================================
class Square extends Polygon {
constructor(length) {
super(length, length);
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
set area(value) {
this.area = value;
}
}
let s = new Square(5);
s.sayName();
console.log('The area of this square is ' + s.area);
// Example 4: Subclassing methods of a parent class
// ===============================================================
class Rectangle extends Polygon {
constructor(height, width) {
super(height, width);
this.name = 'Rectangle';
}
sayName() {
console.log('Sup! My name is ', this.name + '.');
super.sayHistory();
}
}
let r = new Rectangle(50, 60);
r.sayName();