编程

类的继承

2019-11-04  本文已影响0人  五十岚色叶
  1. 类的继承
    通过extends关键字,子类继承了父类的所有属性和方法

  2. super关键字
    super() 作为函数使用
    super() 作为函数使用时只能在子类的构造函数中使用,子类的constructor也必须要执行一次super()
    super 作为对象使用

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
class Parent {
      static myMethod(msg) {
            console.log('static', msg);
      }

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

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

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

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

注意:在子类的静态方法中通过super调用父类的方法时,方法内部的this指向当前的子类(子类的静态属性),而不是子类的实例


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

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

B.x = 3;
B.m() // 3
      static m() {
            super.print();
      }
}

B.x = 3;
B.m() // 3
上一篇 下一篇

猜你喜欢

热点阅读