学习笔记——super的用法

参考文档:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/super

使用方法1:super就是调用一下父类的构造函数

在类继承extends时,如果子类中存在构造函数,则必须在使用"this"之前首先调用super( ) 不然会报错。

class myDate2 extends Date {
  constructor() {
   // 少了super,而下文中使用了this
  }

  getFormattedDate() {
    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear();
  }
}

var x2 = new myDate2() // 报错,哪怕上面去除 getFormattedDate 方法依然会报错
 
 

使用super后不仅可以调用父类的构造函数,还可以直接通过super调用父类的方法。

使用方法2:调用父类上的静态方法

// 先介绍一下类的静态方法
//
1. static 关键字用来定义一个类的一个静态方法。 // 2. 调用静态方法不需要实例化该类,但不能通过一个类实例调用静态方法。 // 3. 静态方法通常用于为一个应用程序创建工具函数。 class Point { constructor(x, y) { this.x = x; this.y = y; } static distance(a, b) { const dx = a.x - b.x; const dy = a.y - b.y; return Math.hypot(dx, dy); } } const p1 = new Point(5, 5); const p2 = new Point(10, 10); console.log(Point.distance(p1, p2));

举例:

class Human {
  constructor() {}
  static ping() {
    return 'ping';
  }
}

class Computer extends Human {
  constructor() {}
  static pingpong() {
    return super.ping() + ' pong'; 
  }
}
Computer.pingpong(); // 'ping pong'

 

其他注意点:

不得使用delete删除super的属性/方法

一个属性定义为不可写时,super将不能重写这个属性的值。

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/espelansa/p/7993349.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值