学习笔记——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将不能重写这个属性的值。

 

 

 

 

 

 

 

posted @ 2017-12-06 21:55  espelansa  阅读(420)  评论(0编辑  收藏  举报