码迷,mamicode.com
首页 > 其他好文 > 详细

学习笔记——super的用法

时间:2017-12-07 00:22:45      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:script   turn   类的方法   定义   poi   months   sep   mozilla   子类   

参考文档:

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

 

 

 

 

 

 

 

学习笔记——super的用法

标签:script   turn   类的方法   定义   poi   months   sep   mozilla   子类   

原文地址:http://www.cnblogs.com/espelansa/p/7993349.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!