chiyan-lin / code-snippet

the record of something snippety
1 stars 0 forks source link

class #18

Open chiyan-lin opened 4 years ago

chiyan-lin commented 4 years ago

在子类普通方法中通过super调用父类的方法时,方法内部的this指向当前的子类实例。

class A {
  constructor() {
    this.x = 1;
  }
  print() {
    console.log(this.x);
  }
}

class B extends A {
  constructor() {
    super();
    this.x = 2;
  }
  m() {
    super.print();
  }
}

let b = new B();
b.m() // 2

this指向子类实例,所以如果通过super对某个属性赋值,这时super就是this,赋值的属性会变成子类实例的属性。

class A {
  constructor() {
    this.x = 1;
  }
}

class B extends A {
  constructor() {
    super();
    this.x = 2;
    super.x = 3;
    console.log(super.x); // because: A.prototype.x so undefined
    console.log(this.x); // 3
  }
}

let b = new B();

super作为对象,用在静态方法之中,这时super将指向父类,而不是父类的原型对象。

class Parent {
  static myMethod(msg) {
    x = 1
    // 子类的静态方法中通过super调用父类的方法时,方法内部的this指向当前的子类,而不是子类的实例。
    console.log(this.x);
    console.log('static', msg);
  }

  myMethod(msg) {
    console.log('instance', msg);
  }
}

class Child extends Parent {
  x = 2
  static myMethod(msg) {
    super.myMethod(msg);
  }

  myMethod(msg) {
    super.myMethod(msg);
  }
}

Child.myMethod(1); // 2 static 1

var child = new Child();
child.myMethod(2); // instance 2