我正在学习创建新类、扩展它和子类化。我不理解以下内容:
- 为什么在示例#2中扩展类时,
constructor()
和super()
都使用length
作为参数? - 如果示例#2中的
super()
应该访问父类Polygon,那么它不应该使用height
和width
作为参数来访问它们在Polygon类中的值吗(就像示例#4中所做的那样)?如果不是这样,为什么?
// 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();
Polygon
类中使用的变量名height
和width
与super()
之间是否存在关系?即使我在super(length1, length2)
中编写,仍然保留(height,width)
在Polygon
类中,super()
是否能正常工作? - user3926863super
时,lenght1
和length2
是作用域内的变量,那么你可以这样做 - 子类的构造函数参数不一定与父类的构造函数参数有任何关系。 - CertainPerformancesuper
传递。如果您不带参数调用super
,则父类构造函数的参数(如果有)将全部为“undefined”https://jsfiddle.net/75s296kg/ 这取决于父级 - 有时可以这样做,有时不带参数调用super
会导致错误(例如,如果父级期望一个参数是字符串,并尝试调用字符串方法)。 - CertainPerformance