【发布时间】:2019-06-07 10:44:26
【问题描述】:
我正在学习如何创建一个新类、对其进行扩展和子类化。我不明白以下内容:
- 为什么在扩展示例#2 中的类时
constructor()和super()都使用length作为参数? - 如果示例#2 中的
super()应该访问父类Polygon,它不应该将height和width用作参数而不是length在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();
【问题讨论】:
标签: javascript class extends