ES6中构造函数内super关键字的使用

super关键字用于访问和调用一个对象的父对象上的函数。

super.propsuper[expr]表达式在类和对象字面量任何方法定义中都是有效的。

语法

super([arguments]); 
// 调用 父对象/父类 的构造函数

super.functionOnParent([arguments]); 
// 调用 父对象/父类 上的方法

描述

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

示例

在类中使用super

class Polygon {
  constructor(height, width) {
    this.name = 'Polygon';
    this.height = height;
    this.width = width;
  }
  sayName() {
    console.log('Hi, I am a ', this.name + '.');
  }
}

class Square extends Polygon {
  constructor(length) {
    this.height; 
    // ReferenceError,super 需要先被调用!
    
/*
   这里,它调用父类的构造函数的 length, 
   作为Polygon 的 width和 height.
*/ 
    super(length, length);
    
/*
    注意: 在派生的类中, 在你可以使用'this'之前, 必须先调用super()。
    忽略这, 这将导致引用错误。
*/
    this.name = 'Square';
  }

  get area() {
    return this.height * this.width;
  }

  set area(value) {
    this.area = value;
  } 
}

  

调用父类上的静态方法

你也可以用 super 调用父类的静态方法。

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

  

posted @ 2019-12-23 10:57  lanyan  阅读(440)  评论(0编辑  收藏  举报