使用super()在扩展一个类时的区别。

3
我正在学习创建新类、扩展它和子类化。我不理解以下内容:
  • 为什么在示例#2中扩展类时,constructor()super()都使用length作为参数?
  • 如果示例#2中的super()应该访问父类Polygon,那么它不应该使用heightwidth作为参数来访问它们在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();
1个回答

2

一个正方形只需要一个参数 - 其中一个边的长度,这是有道理的。但如果正方形是多边形的一种类型,则此处的多边形需要两个参数,即高度和宽度。

如果实例化一个正方形,该正方形需要调用super来运行多边形构造函数,该构造函数需要两个参数:heightwidth。在Square构造函数中,它们是相同的 - length变量,因此需要进行调用。

super(length, length);

第四个例子不同于其他的例子,因为它是一个矩形而不是一个正方形。与多边形一样,矩形接受两个参数——高度和宽度,所以矩形构造函数和多边形构造函数都使用(height, width)进行调用,而super调用也反映了这一点:

super(height, width);

你无处不在 - 0.sh
谢谢@CertainPerformance。另外一个澄清问题:在矩形的情况下,Polygon类中使用的变量名heightwidthsuper()之间是否存在关系?即使我在super(length1, length2)中编写,仍然保留(height,width)Polygon类中,super()是否能正常工作? - user3926863
1
如果在调用 super 时,lenght1length2 是作用域内的变量,那么你可以这样做 - 子类的构造函数参数不一定与父类的构造函数参数有任何关系。 - CertainPerformance
再次感谢 @CertainPerformance。根据你的说法,在扩展现有类时——如果子类的构造函数参数不必与父类的构造函数参数有任何关系——在哪种情况下需要指定 super() 和 constructor() 的参数?如果我只是将它们留空而不带参数,它仍然能正常工作吗? - user3926863
如果父构造函数需要来自子构造函数作用域的数据,则应通过super传递。如果您不带参数调用super,则父类构造函数的参数(如果有)将全部为“undefined”https://jsfiddle.net/75s296kg/ 这取决于父级 - 有时可以这样做,有时不带参数调用super会导致错误(例如,如果父级期望一个参数是字符串,并尝试调用字符串方法)。 - CertainPerformance

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接