【问题标题】:Differences in using super() when extending a class扩展类时使用 super() 的区别
【发布时间】:2019-06-07 10:44:26
【问题描述】:

我正在学习如何创建一个新类、对其进行扩展和子类化。我不明白以下内容:

  • 为什么在扩展示例#2 中的类时constructor()super() 都使用length 作为参数?
  • 如果示例#2 中的super() 应该访问父类Polygon,它不应该将heightwidth 用作参数而不是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


    【解决方案1】:

    一个正方形只接受一个参数是有道理的——它的一个边的长度。但是如果 Square 是一种多边形,这里的多边形需要 两个 参数,一个高度和一个宽度。

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

    super(length, length);
    

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

    super(height, width);
    

    【讨论】:

    • 你无处不在
    • 谢谢@CertainPerformance。另一个需要澄清的问题:在 Rectangle 的情况下,Polygon 类和 super() 中使用的变量名称 heightwidth 之间是否存在关系?即使我写super(lenght1, length2)super () 会正常工作,同时仍将(height, width) 保留在 Polygon 类中吗?
    • @user3926863 如果lenght1length2 在您调用super 时是范围内的变量,是的,您可以这样做——子类的构造函数参数不必有任何东西与父类的构造函数参数有关。
    • 再次感谢@CertainPerformance。鉴于您所说,在扩展现有类时-如果子类的构造函数参数不必与父类的构造函数参数有任何关系-在这种情况下,我需要指定 super() 和构造函数的参数()?如果我只是让它们不带任何参数,它还能正常工作吗?
    • @user3926863 如果父构造函数需要来自子构造函数作用域的数据,则应通过super 传递。如果您不带参数调用super,则父类的构造函数的参数(如果有)将全部为undefined jsfiddle.net/75s296kg 这取决于父级 - 有时您可以这样做,有时不带参数调用super 会导致在错误中(例如,如果父级期望参数是字符串,并尝试对其调用字符串方法)
    猜你喜欢
    • 1970-01-01
    • 2017-05-23
    • 2011-03-30
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多