gpt4 book ai didi

javascript - 扩展类时使用 super() 的区别

转载 作者:行者123 更新时间:2023-11-29 10:57:36 24 4
gpt4 key购买 nike

我正在学习如何创建新类、扩展它和子类化。我不明白以下内容:

  • 为什么在扩展示例 #2 中的类时 constructor()super() 都使用 length 作为参数?
  • 如果示例 #2 中的 super() 应该访问父类 Polygon,它不应该用作参数 heightwidth 在 Polygon 类而不是 length 中访问它们(就像示例 #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,这里的 Polygons 需要两个参数,一个高度和一个宽度。

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

super(length, length);

示例 4 不同,因为它是一个 Rectangle,而不是 Square。矩形接受两个参数,一个高度和一个宽度,就像多边形一样,所以 Rectangle 构造函数和 Polygon 构造函数都是用 (height, width)super 调用反射(reflect)了:

super(height, width);

关于javascript - 扩展类时使用 super() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54164678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com