JavaScript/super

来自康健生活

引言

constructor

语法糖
function Point(x, y) {
  this.x = x;
  this.y = y;
}
Point.prototype.toString = function () {
  return `(${this.x},${this.y})`;
}
class Point {
  constructor(x ,y) {
    this.x = x;
    this.y = y;
  }
  toString() {
    return `(${this.x},${this.y})`;
  }
}

super

子类的构造函数中必须执行一次 super 函数,子类没有自己的 this 对象,而是继承父类的 this 对象。 super() 等价于 A.prototype.constructor.call(this, props)。

子类通过 super 调用父类方法,super 会绑定子类的 this。
class A {
  constructor() {
    console.log('class A');
  }
}
class B extends A {
  constructor() {
    super();
  }
}
new A();
new B();
class A
class A


class A {
  foo() {
    return 'kangkk';
  }
}
class B extends A {
  constructor() {
    super();
    console.log(super.foo());
  }
}
const bar = new B();
console.log(bar);
kangkk
B {}