我正在学习有关创建新类,扩展它和子类化的知识.我不了解以下内容:
>为什么在示例2中扩展类时,constructor()和super()都使用length作为参数?
>如果示例2中的super()应该访问父类Polygon,那么它不应该使用高度和宽度作为参数来访问Polygon类中的父类而不是长度(就像示例4中那样)吗?如果没有,为什么?
源代码是: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();
最佳答案
正方形仅接受一个参数是有意义的,即其边之一的长度.但是,如果Square是Polygon的类型,则此处的Polygon需要两个参数,即height和width.
原文链接:https://www.f2er.com/js/531097.html如果实例化一个Square,则该Square需要调用super来运行Polygon构造函数,该构造函数需要两个参数,即height和width.在Square构造函数中,它们是相同的-长度变量,因此调用
super(length,length);
示例4有所不同,因为它是矩形,而不是正方形.矩形接受两个参数,即高度和宽度,就像多边形一样,因此Rectangle构造函数和Polygon构造函数都用(height,width)调用,而super调用反映了:
super(height,width);