JavaScript 类(class)super关键字

super关键字用于访问和调用一个对象的父对象上的函数。
在构造函数中使用,super关键字将单独出现,并且必须在使用this关键字之前。
super关键字也可以用来调用父对象上的函数。

class Polygon {
  constructor(height, width) {
    this.name = 'Rectangle';
    this.height = height;
    this.width = width;
  }
  sayName() {
    return 'Hi, I am a ' + this.name + '.';
  }
  get area() {
    return this.height * this.width;
  }
  set area(value) {
    this._area = value;
  }
}
 
class Square extends Polygon {
  constructor(length) {
    // 这里,它调用父类的构造函数的,
    // 作为 Polygon 的 height, width
    super(length, length);
      
    this.height; // 需要放在 super 后面,不然引发 ReferenceErro
 
    // 注意:在派生的类中,在你可以使用'this'之前,必须先调用 super()。
    // 忽略这,这将导致引用错误。
    this.name = 'Square';
  }
}
class Rectangle {
  constructor() {}
  static logNbSides() {
    return 'I have 4 sides';
  }
}
 
class Square extends Rectangle {
  constructor() {}
  static logDescription() {
    return super.logNbSides() + ' which are all equal';
  }
}
Square.logDescription(); // 'I have 4 sides which are all equal'
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值