js -- super释义

SUPER

标准阅读:ECMAScript 2015 (6th Edition, ECMA-262)

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

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

语法

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

描述

在构造函数中使用,super关键字单独出现,并且必须在使用this关键字之前使用

super也可用于调用父对象上的函数

示例

在类中使用super

来源:classes sample

class Polygon {
  constructor(height, width) {
    this.name = 'Rectangle';
    this.height = height;
    this.width = width;
  }
  sayName() {
    console.log('Hi,I am', this.name, '.');
  }
  get area() {
    return this.height * this.width;
  }
  set area(value) {
    this._area = value;
  }
}

class Square extends Polygon {
  constructor(length) {
    // this.height; // ReferenceError, super需先被调用
    super(length, length); // 调用父类的构造函数,作为Polygon的height和width
    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();

删除super上的属性将抛出异常

不能使用 delete 操作符加 super.prop 或 super[expr] 去删除父类的属性

class Base {
  constructor() {}
  foo() {}
}
class Derived extends Base {
  constructor() {}
  delete() {
    delete super.foo; // BAD
  }
}
new Derived().delete(); // ReferenceError: invalid delete involving 'super'

super.prop不能覆写不可写属性

使用 Object.defineProperty 定义一个属性为不可写时,super将不能重写这个属性的值

class X {
  constructor() {
    Object.defineProperty(this,'prop',{
      configurable: true,
      writable: false,
      value: 1
    });
  }
}
class Y extends X {
  constructor() {
    super();
  }
  foo(){
    super.prop = 2;
  }
}
var y = new Y();
y.foo(); // TypeError: "prop" is read-only
console.log(y.prop);

在对象字面量中使用 super.prop

super 也可在 object initializer / literal 符号中使用,在下面的例子中,两个对象各定义一个方法,在第二个对象中,使用super调用第一个对象的方法。

需要先利用 object.setPrototypeOf() 设置 obj2 的原型为 obj1,然后才能使用 super 调用 obj1 上的 method1

var obj1 = {
  method1(){
    console.log("method 1");
  }
}
var obj2 = {
  method2(){
    super.method1();
  }
}
Object.setPrototypeOf(obj2, obj1);
obj2.method2();
posted @ 2021-01-05 14:05  汪淼焱  阅读(546)  评论(0)    收藏  举报